0003 - Longest Substring Without Repeating Characters
description
Given a string s
, find the length of the longest substring without duplicate characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
submission
impl Solution {
pub fn length_of_longest_substring(s: String) -> i32 {
let mut ans = 0;
// this marks the left side of sliding window
let mut first = 0;
// cache the last occurrence of different char
// we use array to optimize hashmap cost
let mut indices = [0; 256];
for (idx, ch) in s.chars().enumerate() {
// update left of sliding window
first = first.max(indices[ch as usize]);
// update answer
ans = ans.max(idx as i32 - first + 1);
// cache indices
indices[ch as usize] = idx as i32 + 1;
}
ans
}
}