用 Rust 刷 leetcode 第三题

Problem

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

Example

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.

Solution

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 协议》,转载必须注明作者和本文链接

令狐一冲

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!