[閒聊] 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