Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example
For example, the longest substring without repeating letters for"abcabcbb"is"abc", which the length is3.
For"bbbbb"the longest substring is"b", with the length of1.
Solution: Slow fast window two pointers
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int res = 0, slow = 0;
HashSet<Character> set = new HashSet<Character>();
for(int fast = 0; fast < s.length(); fast++) {
char c = s.charAt(fast);
if(!set.contains(c)) {
set.add(c);
res = Math.max(res, set.size());
}
else {
res = Math.max(res, fast - slow);
while(slow < fast && s.charAt(slow) != s.charAt(fast)) {
set.remove(s.charAt(slow));
slow++;
}
slow++;
}
}
return res;
}