3. Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating 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.
Example 4:
Input: s = "" Output: 0
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
Rust Solution
struct Solution;
use std::collections::HashMap;
impl Solution {
fn length_of_longest_substring(s: String) -> i32 {
let mut hm: HashMap<char, usize> = HashMap::new();
let mut max: usize = 0;
let mut l: usize = 0;
for (r, c) in s.char_indices() {
if let Some(end) = hm.insert(c, r) {
l = usize::max(l, end + 1);
}
max = usize::max(r - l + 1, max);
}
max as i32
}
}
#[test]
fn test() {
let s = " ".to_string();
assert_eq!(Solution::length_of_longest_substring(s), 1);
let s = "abba".to_string();
assert_eq!(Solution::length_of_longest_substring(s), 2);
let s = "abcabcbb".to_string();
assert_eq!(Solution::length_of_longest_substring(s), 3);
let s = "bbbb".to_string();
assert_eq!(Solution::length_of_longest_substring(s), 1);
let s = "pwwkew".to_string();
assert_eq!(Solution::length_of_longest_substring(s), 3);
}
Having problems with this solution? Click here to submit an issue on github.