-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlongest-substring.rs
More file actions
69 lines (63 loc) · 2.29 KB
/
longest-substring.rs
File metadata and controls
69 lines (63 loc) · 2.29 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
//! # Longest Substring without duplicates
//!
//! Given a string `s`, find the length of the longest substring without
//! duplicate characters.
//!
//! Here, we check if the duplicate exists using the sliding window.
//!
//! we start with the hashmap that stores the character, and it's occurrence
//! index. if the duplicate is found, left index of that character is moved
//! so that the starting point of the count will be from that index + 1.
//!
//! at the end of the loop, we check if we achieved max length by comparing prev
//! max length, and updating it.
use std::{cmp::max, collections::HashMap};
fn length_of_longest_substring(string: String) -> usize {
// return the length of string if the length is 0 or 1 since it has unique elements
if string.len() < 2 {
return string.len();
}
let mut left = 0;
let mut max_len = 0;
let mut char_map: HashMap<char, usize> = HashMap::new();
for (right, char) in string.chars().enumerate() {
if let Some(&index) = char_map.get(&char) {
if index >= left {
left = index + 1;
}
}
char_map.insert(char, right);
max_len = max(max_len, right - left + 1);
// TODO: uncomment to see assigned values
// println!("character: {char}, left: {left}, right: {right}, max_len: {max_len}");
}
return max_len;
}
fn main() {
let length = length_of_longest_substring("abcabcbb".to_owned());
println!("length_of_the_longest_substring: {length}");
}
#[cfg(test)]
mod tests {
use crate::length_of_longest_substring;
#[test]
fn empty_string() {
assert_eq!(length_of_longest_substring("".to_owned()), 0);
}
#[test]
fn single_item() {
assert_eq!(length_of_longest_substring("a".to_owned()), 1);
}
#[test]
fn two_items() {
assert_eq!(length_of_longest_substring("au".to_owned()), 2);
}
#[test]
fn test_for_correctness() {
assert_eq!(length_of_longest_substring("abcabcbb".to_owned()), 3);
assert_eq!(length_of_longest_substring("bbbbb".to_owned()), 1);
assert_eq!(length_of_longest_substring("bbbabb".to_owned()), 2);
assert_eq!(length_of_longest_substring("pwwkew".to_owned()), 3);
assert_eq!(length_of_longest_substring("abcbcad".to_owned()), 4);
}
}