aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2019-09-20 20:28:55 +0800
committercrupest <crupest@outlook.com>2019-09-20 20:28:55 +0800
commitf7d11985d89b161bc9db45429bacfcaa070b76a6 (patch)
treef2a5997963c6744960b6c9e7fca141269082e80b
parentfa7b2234e710c5b6406d7cbb40b5b4e134b5e254 (diff)
downloadcrupest-f7d11985d89b161bc9db45429bacfcaa070b76a6.tar.gz
crupest-f7d11985d89b161bc9db45429bacfcaa070b76a6.tar.bz2
crupest-f7d11985d89b161bc9db45429bacfcaa070b76a6.zip
import(solutions): Optimize p3.
-rw-r--r--works/solutions/src/length_of_longest_substring.rs32
1 files changed, 15 insertions, 17 deletions
diff --git a/works/solutions/src/length_of_longest_substring.rs b/works/solutions/src/length_of_longest_substring.rs
index cebcc72..cbd5e14 100644
--- a/works/solutions/src/length_of_longest_substring.rs
+++ b/works/solutions/src/length_of_longest_substring.rs
@@ -1,29 +1,27 @@
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 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() {
- 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;
- }
+ 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 as i32
+ result
}
}