用 Rust 刷 leetcode 第三題

linghuyichong發表於2019-12-11

Given a string, find the length of the longest substring without repeating characters.

Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:
Input: "bbbbb"
Output: 1 Explanation: The answer is "b", with the length of 1.

Example 3:
Input: "pwwkew"
Output: 3 Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

use std::cmp;
impl Solution {    
    pub fn length_of_longest_substring(s: String) -> i32 {
        let s = s.as_bytes();
        let mut index: [i32; 128] = [-1; 128];
        let mut left = -1;
        let mut max_size = 0;

        for i in 0..s.len() {
            let k = s[i] as usize;
            left = cmp::max(left, index[k]);
            let temp = i as i32;
            index[k] = temp;
            max_size = cmp::max(max_size, (temp - left));
        }

        max_size
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章