无重复字符的最长子串
滑块移动
Set 无重复子串,若有重复 j+1,移除前面的元素,直到不重复 j+1,j 再往后移动
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> slider = new HashSet<Character>();
int n = s.length();
int j = -1, lenght = 0;
for (int i = 0; i < n; i++) {
if (i != 0) {
//滑块移动
slider.remove(s.charAt(i - 1));
}
while (j + 1 < n && !slider.contains(s.charAt(j + 1))) {
slider.add(s.charAt(j + 1));
++j;
}
lenght = Math.max(lenght, j - i + 1);
}
return lenght;
}
}
ASCII表
ch[256]
把字符串作为角标
class Solution {
public int lengthOfLongestSubstring(String s) {
// ASCII表共能表示256个字符
int[] ch = new int[256];
Arrays.fill(ch, -1);
int res = 0, left = -1;
int count = s.length();
for (int i = 0; i < count; i++) {
left = Math.max(left, ch[s.charAt(i)]);
ch[s.charAt(i)] = i;
res = Math.max(res, i - left);
}
return res;
}
}