Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int left = 0;
int max = 0;
for(int right = 0; right < s.length(); right++){
char c = s.charAt(right);
if(map.containsKey(c)){
left = Math.max(map.get(c) + 1, left);
}
max = Math.max(max, right - left + 1);
map.put(c, right);
}
return max;
}
}
这句话为了避免下图的情况:left = Math.max(map.get© + 1, left);