File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments