滑动窗口法(不完整解法)
public class Solution {
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int result = 0, i = 0, j = 0;
while (i < n && j < n) {
//charAt:返回指定位置处的字符
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
result = Math.max(result, j - i); //记录每一次窗口的长度,如果窗口大于最大的,则保存
} else {
set.remove(s.charAt(i)); //这个只考虑了移除最后一个元素和首元素相同的情况,只是移除了一个,有移除多个元素的情况。
i++;
}
}
return result;
}
}
滑动窗口法 (完整解法)
/*思路:使用一个列表保存无重复子字符串,如果新字符在子串中,那么已经统计了当前子串的最大值,需要往后进行访问,寻找其它子串,为了防止重复,则把最开头到子串中字符重复位置的都删除,并加入新
字符,保证子串中没有重复的字符。*/
public class Solution {
public int LengthOfLongestSubstring(string s) {
List<char> r = new List<char>();
int c = 0,mx = 0,t;
foreach(char item in s)
{
if(r.Contains(item))
{
t = r.IndexOf(item)+1;
r.RemoveRange(0,t); //移除左边的所有元素
c-=t;
}
r.Add(item); //在里面加入元素
c++;
mx = c>mx?c:mx;
}
return mx;
}
}