aboutsummaryrefslogtreecommitdiff
path: root/works/solutions/src/length_of_longest_substring.rs
blob: cebcc7213967372e3ccb25f53dd2406595db7381 (plain)
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
use super::Solution;

use std::collections::HashMap;

impl Solution {
    pub fn length_of_longest_substring(s: String) -> i32 {
        let mut map = HashMap::new();
        let mut last_index = 0;
        let mut result = 0;
        let bytes = s.as_bytes();
        for (i, c) in bytes.iter().enumerate() {
            match map.get(&c) {
                Some(vi) if *vi >= last_index => {
                    last_index = *vi + 1;
                    map.insert(c, i);
                }
                _ => {
                    map.insert(c, i);
                    let length = i - last_index + 1;
                    if length > result {
                        result = length;
                    }
                }
            }
        }
        result as i32
    }
}

#[cfg(test)]
mod tests {
    use super::Solution;

    #[test]
    fn test() {
        assert_eq!(
            Solution::length_of_longest_substring("abcabcbb".to_string()),
            3
        );
        assert_eq!(
            Solution::length_of_longest_substring("bbbbb".to_string()),
            1
        );
        assert_eq!(
            Solution::length_of_longest_substring("pwwkew".to_string()),
            3
        );
    }
}