Skip to content

Commit 24efa4a

Browse files
committed
add: LongestSubstringWithUniqueChars
1 parent 90f7668 commit 24efa4a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
public class LongestSubstringWithUniqueChars {
5+
public int longestSubstringWithUniqueChars(String s) {
6+
int maxLen = 0;
7+
Set<Character> hashSet = new HashSet<>();
8+
int left, right;
9+
left = right = 0;
10+
while (right < s.length()) {
11+
// If we encounter a duplicate character in the window, shrink
12+
// the window until it's no longer a duplicate.
13+
while (hashSet.contains(s.charAt(right))) {
14+
hashSet.remove(s.charAt(left));
15+
left++;
16+
}
17+
// Once there are no more duplicates in the window, update
18+
// 'max_len' if the current window is larger.
19+
maxLen = Math.max(maxLen, right - left + 1);
20+
hashSet.add(s.charAt(right));
21+
// Expand the window.
22+
right++;
23+
}
24+
return maxLen;
25+
}
26+
}

0 commit comments

Comments
 (0)