Skip to content

Commit 140d603

Browse files
committed
Add Longest Substring With Unique Chars
1 parent 9729740 commit 140d603

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
fun longestSubstringWithUniqueChars(s: String): Int {
2+
var maxLen = 0
3+
val hashSet = mutableSetOf<Char>()
4+
var left = 0
5+
var right = 0
6+
while (right < s.length) {
7+
// If we encounter a duplicate character in the window, shrink
8+
// the window until it's no longer a duplicate.
9+
while (s[right] in hashSet) {
10+
hashSet.remove(s[left])
11+
left++
12+
}
13+
// Once there are no more duplicates in the window, update
14+
// 'maxLen' if the current window is larger.
15+
maxLen = maxOf(maxLen, right - left + 1)
16+
hashSet.add(s[right])
17+
// Expand the window.
18+
right++
19+
}
20+
return maxLen
21+
}

0 commit comments

Comments
 (0)