滑动窗口——最长子串专题
1.1无重复字符的最长子串
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
if (n == 0) {
return 0;
}
int left = 0, right = 1;
int ans = 1;
Map<Character, Integer> map = new HashMap<>();
map.put(s.charAt(left), left);
while (right < n) {
if (map.containsKey(s.charAt(right))) {
left = map.get(s.charAt(right))+ 1;
}
map.put(s.charAt(right), right);
right++;
ans =Math.max(ans, right - left);
}
return ans;
}
1.2至多包含两个不同字符的最长子串
public static int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.length() < 3) {
return s.length();
}
int left = 0, right = 1;
Map<Character, Integer> map = new HashMap<>();
int ans = 2;
map.put(s.charAt(left), left);
while (right < s.length()) {
map.put(s.charAt(right), right++);
if (map.size() == 3) {
Integer del_idx = Collections.min(map.values());
map.remove(s.charAt(del_idx));
left = del_idx + 1;
}
ans = Math.max(ans, right - left);
}
return ans;
}