diff options
author | crupest <crupest@outlook.com> | 2020-05-07 22:37:39 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-05-07 22:37:39 +0800 |
commit | 20b7e2bfba2805c755b0800e25ef5505c41f469c (patch) | |
tree | 1a3a9c604461996a62e5d99fa3c480e759eced0f /works/solutions/rust/src/length_of_longest_substring.rs | |
parent | a39a26346786fe33c8da905cf010e0e6b0376716 (diff) | |
download | crupest-20b7e2bfba2805c755b0800e25ef5505c41f469c.tar.gz crupest-20b7e2bfba2805c755b0800e25ef5505c41f469c.tar.bz2 crupest-20b7e2bfba2805c755b0800e25ef5505c41f469c.zip |
import(solutions): Move rust codes into sub dir.
Diffstat (limited to 'works/solutions/rust/src/length_of_longest_substring.rs')
-rw-r--r-- | works/solutions/rust/src/length_of_longest_substring.rs | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/works/solutions/rust/src/length_of_longest_substring.rs b/works/solutions/rust/src/length_of_longest_substring.rs new file mode 100644 index 0000000..cbd5e14 --- /dev/null +++ b/works/solutions/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
+ );
+ }
+}
|