-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_substring_without_repeating_characters.rs
49 lines (38 loc) · 1.51 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
#![allow(dead_code)]
pub fn length_of_longest_substring(s: String) -> i32 {
let mut max_length = 0;
let mut start = 0;
let mut map = std::collections::HashMap::new();
for (end, c) in s.chars().enumerate() {
if let Some(i) = map.get(&c) {
start = std::cmp::max(start, *i + 1);
}
map.insert(c, end);
max_length = std::cmp::max(max_length, end - start + 1);
}
max_length as i32
}
/*
Algorithm - Sliding Window
Time Complexity = O(n)
Space Complexity = O(n)
Explanation:
1. Create a HashMap to store the characters and their indices
2. Iterate through the string
3. If the character is already in the HashMap, set the start to the maximum of the current start and the index of the character + 1
4. Insert the character and its index into the HashMap
Note: The HashMap stores the index of the character + 1 because if the character is already in the HashMap, the start should be set to the index of the character + 1
5. Set the max_length to the maximum of the current max_length and the end - start + 1
6. Return the max_length
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_length_of_longest_substring() {
assert_eq!(length_of_longest_substring("abcabcbb".to_string()), 3);
assert_eq!(length_of_longest_substring("bbbbb".to_string()), 1);
assert_eq!(length_of_longest_substring("pwwkew".to_string()), 3);
assert_eq!(length_of_longest_substring("".to_string()), 0);
}
}