summaryrefslogtreecommitdiff
path: root/03_longest-substring-without-repeating-chars/src/main.rs
blob: f07bedff0b9207c501b61d7457beef624f1da0fd (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
use std::collections::HashSet;

fn main() {
    let s = "dvdf".to_string();
    dbg!(Solution::length_of_longest_substring(s));
}

struct Solution(());

impl Solution {
    pub fn length_of_longest_substring(s: String) -> i32 {
        use std::collections::HashMap;

        let s = s.chars().collect::<Vec<char>>();
        let mut max_length = 0;
        let mut length = 0;
        let mut map: HashMap<char, i32> = HashMap::new();
        let mut idx = 0;

        while idx < s.len() {
            let ch = &s[idx];

            if let Some(ref ci) = map.remove(ch) {
                map = HashMap::new();
                if max_length < length {
                    max_length = length;
                }

                idx = (ci + 1) as usize;
                length = 0;
                continue;
            }

            map.insert(ch.clone(), idx as i32);

            length += 1;
            idx += 1;
        }

        if length > max_length {
            max_length = length;
        }

        max_length
    }
}