Skip to content

Commit 131514e

Browse files
committed
Add longest_substring_with_unique_chars
1 parent bf2407c commit 131514e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
fn longest_substring_with_unique_chars(s: String) -> i32 {
2+
use std::collections::HashSet;
3+
4+
let mut max_len = 0;
5+
let mut hash_set = HashSet::new();
6+
let mut left = 0;
7+
let mut right = 0;
8+
let s = s.as_bytes();
9+
10+
while right < s.len() {
11+
// If we encounter a duplicate character in the window, shrink
12+
// the window until it's no longer a duplicate.
13+
while hash_set.contains(&s[right]) {
14+
hash_set.remove(&s[left]);
15+
left += 1;
16+
}
17+
// Once there are no more duplicates in the window, update
18+
// 'max_len' if the current window is larger.
19+
max_len = max_len.max(right - left + 1);
20+
hash_set.insert(s[right]);
21+
// Expand the window.
22+
right += 1;
23+
}
24+
25+
max_len as i32
26+
}

0 commit comments

Comments
 (0)