题目:
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;
}
}