Find the longest substring without repeating characters
Sliding Window is a subarray running on a large array, which is a collection of underlying elements. Here we use two pointers, one pointer A always selects the first char of the max substring, from each iteration of the string. The second pointer B runs ahead of pointer A, until a duplicate character is found or the end of the string is reached.
public int lengthOfLongestSubstring(String s) {
int a_pointer = 0;
int b_pointer = 0;
int max = 0;
Set<Character> hashSet = new HashSet<>();
int i = 0;
while(b_pointer < s.length()) {
if(!hashSet.contains(s.charAt(b_pointer))) {
hashSet.add(s.charAt(b_pointer));
b_pointer++;
max = Math.max(hashSet.size(), max);
} else {
hashSet.remove(s.charAt(a_pointer));
a_pointer++;
}
}
return max;
}
Comments
Post a Comment