LeetCode 3. Longest Substring Without Repeating Characters

題目

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

sliding window的題,通過一個set來作爲窗口存放不重複的字符。首先begin和end都指向第一個元素,然後保持begin不動,一個個往右移動end,直到發現一個重複字符,就往右移動begin直到沒有重複的字符,如此循環。寫代碼的時候注意求長度的時候因爲放在end++後面所以不需要end - begin + 1,直接end - begin即可,以及在begin++的時候,別忘了把begin對應的元素從set中移除。

Runtime: 24 ms, faster than 49.44% of C++ online submissions for Longest Substring Without Repeating Characters.

Memory Usage: 13.3 MB, less than 33.83% of C++ online submissions for Longest Substring Without Repeating Characters.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_set<char> set;
        int begin = 0;
        int end = 0;
        int result = 0;
        while (begin <= end && end < s.size()) {
            if (set.count(s[end])) {
                set.erase(s[begin]);  // must erase it from the set
                begin++;
            }
            else {
                set.insert(s[end]);
                end++;
                result = max(result, end - begin);  // because end++, so dont' need to + 1
            }
        }
        return result;
    }
};

這個寫法還可以通過

發佈了123 篇原創文章 · 獲贊 1 · 訪問量 9372
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章