summaryrefslogtreecommitdiff
path: root/src/length_of_longest_substring.rs
diff options
context:
space:
mode:
author杨宇千 <crupest@outlook.com>2019-09-20 19:23:00 +0800
committer杨宇千 <crupest@outlook.com>2019-09-20 19:23:00 +0800
commitafc0736d1a5f451bb42351b4e899e33f764ab315 (patch)
treeb68bf102c69fdf5e89f437bd9192cfc78da26ff4 /src/length_of_longest_substring.rs
downloadsolutions-afc0736d1a5f451bb42351b4e899e33f764ab315.tar.gz
solutions-afc0736d1a5f451bb42351b4e899e33f764ab315.tar.bz2
solutions-afc0736d1a5f451bb42351b4e899e33f764ab315.zip
...
Diffstat (limited to 'src/length_of_longest_substring.rs')
-rw-r--r--src/length_of_longest_substring.rs49
1 files changed, 49 insertions, 0 deletions
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
+ );
+ }
+}