File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun longestSubstringWithUniqueCharsOptimized (s : String ): Int {
2
+ var maxLen = 0
3
+ val prevIndexes = mutableMapOf<Char , Int >()
4
+ var left = 0
5
+ var right = 0
6
+ while (right < s.length) {
7
+ // If a previous index of the current character is present
8
+ // in the current window, it's a duplicate character in the
9
+ // window.
10
+ if (s[right] in prevIndexes && prevIndexes[s[right]]!! >= left) {
11
+ // Shrink the window to exclude the previous occurrence
12
+ // of this character.
13
+ left = prevIndexes[s[right]]!! + 1
14
+ }
15
+ // Update 'maxLen' if the current window is larger.
16
+ maxLen = maxOf(maxLen, right - left + 1 )
17
+ prevIndexes[s[right]] = right
18
+ // Expand the window.
19
+ right++
20
+ }
21
+ return maxLen
22
+ }
You can’t perform that action at this time.
0 commit comments