File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ public class LongestSubstringWithUniqueCharsOptimized {
5
+ public int longestSubstringWithUniqueCharsOptimized (String s ) {
6
+ int maxLen = 0 ;
7
+ Map <Character , Integer > prevIndexes = new HashMap <>();
8
+ int left , right ;
9
+ left = right = 0 ;
10
+ while (right < s .length ()) {
11
+ // If a previous index of the current character is present
12
+ // in the current window, it's a duplicate character in the
13
+ // window.
14
+ if (prevIndexes .containsKey (s .charAt (right )) && prevIndexes .get (s .charAt (right )) >= left ) {
15
+ // Shrink the window to exclude the previous occurrence
16
+ // of this character.
17
+ left = prevIndexes .get (s .charAt (right )) + 1 ;
18
+ }
19
+ // Update 'maxLen' if the current window is larger.
20
+ maxLen = Math .max (maxLen , right - left + 1 );
21
+ prevIndexes .put (s .charAt (right ), right );
22
+ // Expand the window.
23
+ right ++;
24
+ }
25
+ return maxLen ;
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments