diff --git a/src/lib.rs b/src/lib.rs index 5786df9..3cacac6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,19 +1,6 @@ pub mod p1; pub mod p2; pub mod p238; +pub mod p3; pub struct Solution; - -// Definition for singly-linked list. -#[derive(PartialEq, Eq, Clone, Debug)] -pub struct ListNode { - pub val: i32, - pub next: Option>, -} - -impl ListNode { - #[inline] - fn _new(val: i32) -> Self { - ListNode { next: None, val } - } -} diff --git a/src/p2.rs b/src/p2.rs index 846f311..ab4ea54 100644 --- a/src/p2.rs +++ b/src/p2.rs @@ -1,6 +1,11 @@ -use crate::{ListNode, Solution}; +use crate::Solution; // Definition for singly-linked list. +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option>, +} impl Solution { pub fn add_two_numbers( diff --git a/src/p3.rs b/src/p3.rs new file mode 100644 index 0000000..1cd4d03 --- /dev/null +++ b/src/p3.rs @@ -0,0 +1,74 @@ +use crate::Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + if s.is_empty() { + return 0; + } + let mut letters: HashMap = HashMap::new(); + let mut cur_start: usize = 0; + let mut max_length = 0; + for (i, c) in s.chars().enumerate() { + if max_length > i - cur_start && max_length >= s.len() - cur_start { + return max_length as i32 + 1; + } + if let Some(idx) = letters.get(&c) + && *idx >= cur_start + { + cur_start = idx + 1; + *letters.get_mut(&c).unwrap() = i; + } else { + letters.insert(c, i); + if (i - cur_start) > max_length { + max_length = i - cur_start; + } + } + } + max_length as i32 + 1 + } +} + +// println!("{cur_start} {i} {max_length} {c} {letters:?}"); +#[test] +pub fn test_length_of_longest_substring_1() { + assert_eq!( + Solution::length_of_longest_substring("abcabcbb".to_string()), + 3 + ); +} + +#[test] +pub fn test_length_of_longest_substring_2() { + assert_eq!( + Solution::length_of_longest_substring("bbbbb".to_string()), + 1 + ); +} + +#[test] +pub fn test_length_of_longest_substring_3() { + assert_eq!( + Solution::length_of_longest_substring("pwwkew".to_string()), + 3 + ); +} + +#[test] +pub fn test_length_of_longest_substring_4() { + assert_eq!(Solution::length_of_longest_substring("au".to_string()), 2); +} + +#[test] +pub fn test_length_of_longest_substring_5() { + assert_eq!(Solution::length_of_longest_substring("dvdf".to_string()), 3); +} + +#[test] +pub fn test_length_of_longest_substring_6() { + assert_eq!( + Solution::length_of_longest_substring("tmmzuxt".to_string()), + 5 + ); +}