LeetCode Blind Curated 75:https://leetcode.com/list/xoqag3yj/
3. Longest Substring Without Repeating Characters
寻找一个字串中最长的不重复字母子字串
思路:
用Sliding Windows
每次往右一格检查有没有重复
有就把左边删掉
另外先把String放进Vec再进行for loop
因为String.chars().nth()非常消耗性能
Code:
use std::collections::HashSet;
impl Solution {
pub fn length_of_longest_substring(s: String) -> i32 {
let mut window: HashSet<char> = HashSet::new();
let mut s_vec: Vec<char> = s.chars().collect();
let mut left = 0;
let mut max_sub_len = 0;
for (right, &ch) in s_vec.iter().enumerate() {
while window.contains(&ch) {
window.remove(&s_vec[left]);
left += 1;
}
window.insert(ch);
max_sub_len = max_sub_len.max(right - left + 1);
}
max_sub_len as i32
}
}