File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ fn longest_substring_with_unique_chars_optimized ( s : String ) -> i32 {
2
+ use std:: collections:: HashMap ;
3
+
4
+ let mut max_len = 0 ;
5
+ let mut prev_indexes = HashMap :: new ( ) ;
6
+ let mut left = 0 ;
7
+ let mut right = 0 ;
8
+ // Shadowing 's' by converting it to a byte array/slice.
9
+ let s = s. as_bytes ( ) ;
10
+
11
+ while right < s. len ( ) {
12
+ // If a previous index of the current character is present
13
+ // in the current window, it's a duplicate character in the
14
+ // window.
15
+ if let Some ( & prev_index) = prev_indexes. get ( & s[ right] ) {
16
+ // Shrink the window to exclude the previous occurrence
17
+ // of this character.
18
+ if prev_index >= left {
19
+ left = prev_index + 1 ;
20
+ }
21
+ }
22
+ // Update 'max_len' if the current window is larger.
23
+ max_len = max_len. max ( right - left + 1 ) ;
24
+ prev_indexes. insert ( s[ right] , right) ;
25
+ // Expand the window.
26
+ right += 1 ;
27
+ }
28
+
29
+ max_len as i32
30
+ }
You can’t perform that action at this time.
0 commit comments