Question:
双指针,移动窗口问题。
维护一个[st,etd)的窗口,不断向右进行滑动,当[st,etd)不包含etd位置上的字符时,将etd位置上的字符加入[st,etd)->[st,etd]
如果[st,etd)包含etd,则st向右滑动,直到找到与etd位置相同的字符[st,etd)->[st+1,etd)
简单使用图形演示一下 “abcabcbb”时候的情况
java代码:
public class Main_subString {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> set = new HashSet<Character>();
int st = 0;
int etd = 0;
int len = s.length();
int max = 0;
if (len == 0)
return 0;
while (etd < len) {
if (set.contains(s.charAt(etd))) {
if (max < etd - st)
max = etd - st;
while (s.charAt(st) != s.charAt(etd)) {
set.remove(s.charAt(st));
st++; //调整左指针的位置往右移动,直到发现与etd位置相同的字符即停止
}
st++; //找到了与etd相同的字符,此时st左指针的位置需往右移一位
// 包含字符etd st++
} else {
// 不包含字符etd 则添加
set.add(s.charAt(etd));
}
etd++; //右指针向右移动
}
return Math.max(max, etd - st); //考虑etd=len的情况 所以这里需要比较max与(etd-st)哪个大
}
}