Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
sliding window的套路
import java.util.HashSet;
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) return 0;
if(s.length() == 1) return 1;
int start = 0;
int max = 0;
HashSet<Character> set = new HashSet<Character>();
for(int i = 0; i < s.length(); i++){
char current = s.charAt(i);
if(!set.contains(current)){
set.add(current);
max = Math.max(max, i - start + 1);
} else {
while(s.charAt(start) != current){
set.remove(s.charAt(start++));
}
start++;
}
}
return max;
}
}