作者yam276 (史萊哲林的優等生)
看板Marginalman
標題[閒聊] LeetCode Blind Curated 75
時間Fri Oct 6 14:05:11 2023
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
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.172 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1696572313.A.A37.html
推 wwndbk: 大師 10/06 14:09
→ DJYOSHITAKA: 大濕 10/06 14:18
→ Rushia: 你好優秀 10/06 15:39