Skip to content

Commit 903e7b4

Browse files
committed
Add Longest Substring With Unique Chars Optimized
1 parent 140d603 commit 903e7b4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

0 commit comments

Comments
 (0)