题目描述
给定一个字符串 s
,请你找出其中不含有重复字符的 最长
子串的长度。
示例
标注
0 <= s.length <= 5 * 104
-
s
由英文字母、数字、符号和空格组成
首先我们理解题目,题目很简单,就是从一个字符串中找到最长不重复的字串的长度暴力的解法就是从第一个字符开始作为字串开头依次增加长度如果有重复的就记录长度比较当前最长进行下一次循环这个时间的复杂度为O(n^2)代码如下
public class Solution {
public int LengthOfLongestSubstring(string s) {
int result = 1;
int max = 0;
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
result = 1;
Dictionary<char, bool> d = new Dictionary<char, bool>();
d.Add(chars[i], true);
for (int j = i + 1; j < chars.Length; j++)
{
if (!d.ContainsKey(chars[j]))//不包含该字符
{
result += 1;
d.Add(chars[j], true);
}
else
break;
}
max = Math.Max(max,result);
if (i + max > chars.Length)
break;
}
return max;
}
}
能通过题目
题目解答中给出的是移动容器(以以下为例子)
给出两个指针作为容器的边界最开始都指向第一位a,子串的长度靠右指针来扩容每次判断当前字符是否有该字符没有就放入字典中右指针向右移一位当前记录长度加一如果出现重复的左指针向右移一位全部赋初值重新判断
代码如下
public class Solution {
public int LengthOfLongestSubstring(string s) {
HashSet<char> letter=new HashSet<char>();
int left=0,right=0;
int length=s.Length;
int count=0,max=0;
while(right<length)
{
if(!letter.Contains(s[right]))//不包含
{
letter.Add(s[right]);
right++;
count++;
}
else
{
letter.Remove(s[left]);
left++;
count--;
}
max=Math.Max(max,count);
}
return max;
}
}
还有一种更简单的代码 如下
public class Solution {
public int LengthOfLongestSubstring(string s) {
int max = 0;
Queue<char> q = new Queue<char>();
foreach (char c in s)
{
while (q.Contains(c))
q.Dequeue();
q.Enqueue(c);
if (q.Count > max)
max = q.Count;
}
return max;
}
}
上面两种复杂度都为O(n)