From d8f3b40085619cb680c8f227c65a1f5acc393223 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 23 Feb 2021 21:07:19 +0800 Subject: Move leetcode solutions to subdir. --- leetcode/rust/src/length_of_longest_substring.rs | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 leetcode/rust/src/length_of_longest_substring.rs (limited to 'leetcode/rust/src/length_of_longest_substring.rs') diff --git a/leetcode/rust/src/length_of_longest_substring.rs b/leetcode/rust/src/length_of_longest_substring.rs new file mode 100644 index 0000000..cbd5e14 --- /dev/null +++ b/leetcode/rust/src/length_of_longest_substring.rs @@ -0,0 +1,47 @@ +use super::Solution; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let mut map: [i32; std::u8::MAX as usize] = [-1; std::u8::MAX as usize]; + let mut last_index: i32 = 0; + let mut result: i32 = 0; + let bytes = s.as_bytes(); + for (i, c) in bytes.iter().enumerate() { + let i = i as i32; + let c = *c as usize; + let li = map[c]; + if li >= last_index { + last_index = li + 1; + map[c] = i; + } else { + map[c] = i; + let length = i - last_index + 1; + if length > result { + result = length; + } + } + } + result + } +} + +#[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