Longest Substring Without Repeating Characters
Given a string, find the length of thelongest substringwithout repeating characters.
Examples:
Given"abcabcbb"
, the answer is"abc"
, which the length is 3.
Given"bbbbb"
, the answer is"b"
, with the length of 1.
Given"pwwkew"
, the answer is"wke"
, with the length of 3. Note that the answer must be asubstring,"pwke"
is asubsequenceand not a substring.
Tips:
注意循环条件,用两个指针来做。
Code:
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int res = 0, left = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!map.containsKey(s.charAt(i))) map.put(c, 0);
map.put(c, map.get(c) + 1);
while (map.size() > 2) {
char l = s.charAt(left);
map.put(l, map.get(l) - 1);
if (map.get(l) == 0) map.remove(l);
left++;
}
res = Math.max(res, i - left + 1);
}
return res;
}
}