3. Longest Substring Without Repeating Characters#
Approach:
Sliding Window with a Set
holding the unique characters
1public int lengthOfLongestSubstring(String s) {
2 int max = 0, left = 0, right = 0;
3 Set<Character> charsInWindow = new HashSet<>();
4
5 while (right < s.length()) {
6 if (charsInWindow.contains(s.charAt(right))) {
7 charsInWindow.remove(s.charAt(left));
8 left++;
9 } else {
10 charsInWindow.add(s.charAt(right));
11 right++;
12 max = Math.max(max, charsInWindow.size());
13 }
14 }
15
16 return max;
17}