无重复字符的最长子串

题目:
3. 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

思路:
用哈希集来判断是否有重复字符。
每一次出现重复字符,截取从头开始到重复之前的子串,放入储存数组中后,在原字符串中删除所截子串。
最后比较数组中各子串的长度。

public class Solution {
    public int LengthOfLongestSubstring(string s) {
if (string.IsNullOrEmpty(s))
                    return 0;
                
 string ss = s;
                int n = 1000000;
                string[] strtemp = new string[n];
                int head = 0;
                int T = 0;
                int k=0;
                int Len = ss.Length;
                HashSet<char> hastemp = new HashSet<char>();
                for(int i=0;i<Len;i++)
                {
                    if (hastemp.Add(ss[i]))
                    {
                        k++;
                        if (i != Len - 1)
                            continue;
                        else
                        {
                            string temp = ss.Substring(head, i - head + 1);
                            strtemp[T++] = temp;
                        }
                    }
                    else
                    {
                        //abcdc
                        //strtemp[T] = new string[i-head];
                        if(T==0)
                        {
                            strtemp[T++] = ss.Substring(head, i);
                            int a = ss.IndexOf(ss[i]);
                            for (int j = 0; j < a; j++)
                                hastemp.Remove(ss[j]);
                            ss=ss.Remove(head, a-head+1);
                            Len -= (a+1);
                            i -= (a+1);
                        }
                        else
                        {
                            string temp = ss.Substring(head, i);
                            if (temp.Length >= strtemp[T - 1].Length)
                                strtemp[T++] = temp;
                            int a = ss.IndexOf(ss[i]);
                            for (int j = 0; j < a; j++)
                                hastemp.Remove(ss[j]);
                            ss=ss.Remove(head, a-head+1);
                            Len -= (a + 1);
                            i -= (a+1);
                        }
                    }
                }
                if(k==s.Length)
                return k;
                int MaxL = 0;
                for (int i = 1; i < T; i++)
                    if (strtemp[i].Length > strtemp[MaxL].Length)
                        MaxL = i;
                return strtemp[MaxL].Length;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值