From afc0736d1a5f451bb42351b4e899e33f764ab315 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Fri, 20 Sep 2019 19:23:00 +0800 Subject: ... --- src/length_of_longest_substring.rs | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/length_of_longest_substring.rs (limited to 'src/length_of_longest_substring.rs') diff --git a/src/length_of_longest_substring.rs b/src/length_of_longest_substring.rs new file mode 100644 index 0000000..cebcc72 --- /dev/null +++ b/src/length_of_longest_substring.rs @@ -0,0 +1,49 @@ +use super::Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let mut map = HashMap::new(); + let mut last_index = 0; + let mut result = 0; + let bytes = s.as_bytes(); + for (i, c) in bytes.iter().enumerate() { + match map.get(&c) { + Some(vi) if *vi >= last_index => { + last_index = *vi + 1; + map.insert(c, i); + } + _ => { + map.insert(c, i); + let length = i - last_index + 1; + if length > result { + result = length; + } + } + } + } + result as i32 + } +} + +#[cfg(test)] +mod tests { + use super::Solution; + + #[test] + fn test() { + assert_eq!( + Solution::length_of_longest_substring("abcabcbb".to_string()), + 3 + ); + assert_eq!( + Solution::length_of_longest_substring("bbbbb".to_string()), + 1 + ); + assert_eq!( + Solution::length_of_longest_substring("pwwkew".to_string()), + 3 + ); + } +} -- cgit v1.2.3