-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_substring_without_repeating_characters.rs
56 lines (47 loc) · 1.38 KB
/
longest_substring_without_repeating_characters.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::collections::HashSet;
/// Given a string `s`, find the length of the longest substring without repeating
/// characters.
pub struct Solution;
impl Solution {
pub fn length_of_longest_substring(s: String) -> i32 {
let letters: Vec<char> = s.chars().collect();
let mut items: HashSet<char> = HashSet::new();
let mut result = 0;
let mut current = 0;
let mut left: usize = 0;
for letter in letters.iter() {
if items.contains(&letter) {
while letters[left] != *letter {
items.remove(&letters[left]);
current -= 1;
left += 1;
}
left += 1;
} else {
items.insert(*letter);
current += 1;
result = result.max(current);
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let result = Solution::length_of_longest_substring("abcabcbb".to_string());
assert_eq!(result, 3);
}
#[test]
fn example_2() {
let result = Solution::length_of_longest_substring("bbbbb".to_string());
assert_eq!(result, 1);
}
#[test]
fn example_3() {
let result = Solution::length_of_longest_substring("pwwkew".to_string());
assert_eq!(result, 3);
}
}