3. Longest Substring Without Repeating Characters
given: a string, find the length of the longest substring without repeating characters.
e.g. 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.
one way to use HashSet to track the longest substring without repeating characters so far, use a fast pointer
j to see if character j is in the hash set or not, if not, great, add it to the has set, move j forward and update
the max length, otherwise, delete from the head by using a slow pointer i util we can put character j to the hash set
public class Solution{
public int lengthOfLongestSubstring(String s){
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j<s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
max=Math.max(max, set.size());
}else{
set.remove(s.charAt(i++));
}
}
return max;
}
}
given: a string, find the length of the longest substring without repeating characters.
e.g. 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.
one way to use HashSet to track the longest substring without repeating characters so far, use a fast pointer
j to see if character j is in the hash set or not, if not, great, add it to the has set, move j forward and update
the max length, otherwise, delete from the head by using a slow pointer i util we can put character j to the hash set
public class Solution{
public int lengthOfLongestSubstring(String s){
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j<s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
max=Math.max(max, set.size());
}else{
set.remove(s.charAt(i++));
}
}
return max;
}
}