[闲聊] LeetCode Blind Curated 75

楼主: yam276 ('_')   2023-10-06 14:05:11
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
}
}
作者: wwndbk (黑人问号)   2023-10-06 14:09:00
大师
作者: DJYOSHITAKA (Evans)   2023-10-06 14:18:00
大湿
作者: Rushia (みけねこ的鼻屎)   2023-10-06 15:39:00
你好优秀

Links booklink

Contact Us: admin [ a t ] ucptt.com