|
| 1 | +//! # Longest Substring without duplicates |
| 2 | +//! |
| 3 | +//! Given a string `s`, find the length of the longest substring without |
| 4 | +//! duplicate characters. |
| 5 | +//! |
| 6 | +//! Here, we check if the duplicate exists using the sliding window. |
| 7 | +//! |
| 8 | +//! we start with the hashmap that stores the character, and it's occurrence |
| 9 | +//! index. if the duplicate is found, left index of that character is moved |
| 10 | +//! so that the starting point of the count will be from that index + 1. |
| 11 | +//! |
| 12 | +//! at the end of the loop, we check if we achieved max length by comparing prev |
| 13 | +//! max length, and updating it. |
| 14 | +
|
| 15 | +use std::{cmp::max, collections::HashMap}; |
| 16 | + |
| 17 | +fn length_of_longest_substring(string: String) -> usize { |
| 18 | + // return the length of string if the length is 0 or 1 since it has unique elements |
| 19 | + if string.len() < 2 { |
| 20 | + return string.len(); |
| 21 | + } |
| 22 | + |
| 23 | + let mut left = 0; |
| 24 | + let mut max_len = 0; |
| 25 | + let mut char_map: HashMap<char, usize> = HashMap::new(); |
| 26 | + |
| 27 | + for (right, char) in string.chars().enumerate() { |
| 28 | + if let Some(&index) = char_map.get(&char) { |
| 29 | + if index >= left { |
| 30 | + left = index + 1; |
| 31 | + } |
| 32 | + } |
| 33 | + char_map.insert(char, right); |
| 34 | + max_len = max(max_len, right - left + 1); |
| 35 | + // TODO: uncomment to see assigned values |
| 36 | + // println!("character: {char}, left: {left}, right: {right}, max_len: {max_len}"); |
| 37 | + } |
| 38 | + return max_len; |
| 39 | +} |
| 40 | +fn main() { |
| 41 | + let length = length_of_longest_substring("abcabcbb".to_owned()); |
| 42 | + println!("length_of_the_longest_substring: {length}"); |
| 43 | +} |
| 44 | + |
| 45 | +#[cfg(test)] |
| 46 | +mod tests { |
| 47 | + use crate::length_of_longest_substring; |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn empty_string() { |
| 51 | + assert_eq!(length_of_longest_substring("".to_owned()), 0); |
| 52 | + } |
| 53 | + #[test] |
| 54 | + fn single_item() { |
| 55 | + assert_eq!(length_of_longest_substring("a".to_owned()), 1); |
| 56 | + } |
| 57 | + #[test] |
| 58 | + fn two_items() { |
| 59 | + assert_eq!(length_of_longest_substring("au".to_owned()), 2); |
| 60 | + } |
| 61 | + #[test] |
| 62 | + fn test_for_correctness() { |
| 63 | + assert_eq!(length_of_longest_substring("abcabcbb".to_owned()), 3); |
| 64 | + assert_eq!(length_of_longest_substring("bbbbb".to_owned()), 1); |
| 65 | + assert_eq!(length_of_longest_substring("bbbabb".to_owned()), 2); |
| 66 | + assert_eq!(length_of_longest_substring("pwwkew".to_owned()), 3); |
| 67 | + assert_eq!(length_of_longest_substring("abcbcad".to_owned()), 4); |
| 68 | + } |
| 69 | +} |
0 commit comments