力扣刷題解決方案3. 無重複字符的最長子串

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。

示例 1:

輸入: “abcabcbb” 輸出: 3 解釋: 因爲無重複字符的最長子串是 “abc”,所以其長度爲 3。

示例 2:

輸入: “bbbbb” 輸出: 1 解釋: 因爲無重複字符的最長子串是 “b”,所以其長度爲 1。

示例 3:

輸入: “pwwkew” 輸出: 3 解釋: 因爲無重複字符的最長子串是 “wke”,所以其長度爲 3。
請注意,你的答案必須是 子串 的長度,“pwke” 是一個子序列,不是子串。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解決思路

採用滑動窗口:
意思就是對於字符串,使用左右兩個下標來界定,下標中間是無重複字符,可以採用set來存儲,C++中的unordered_set,底層是hash表,增刪查時間複雜度均接近O(1),而set底層實現紅黑樹,時間複雜度log(N)。

以上,我們初始時左右下標都爲0;
1.右側下標儘可能往右移動,如果unordered_set集合中無當前數據,則加入該數據,直到字符串結束或出現重複;
2.跳出循環時計算此時集合大小,更新最長子串長度;
3.如果重複,那麼嘗試將左下標指向數據刪除,轉1繼續,否則可以結束循環,返回最長子串長度。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    
        std::unordered_set<char> statistic; //這個效率比set高
        int maxlen = 0;
        int pr = 0;// 右下標
        for(int i = 0; i < s.length(); i++)
        {
            while(pr < s.length() && statistic.count(s[pr])==0)
            {
                statistic.insert(s[pr++]);
            }
            
            maxlen = statistic.size() > maxlen? statistic.size():maxlen;

            if(pr < s.length())
            {
                statistic.erase(s[i]); 
            }
            else
            	break;
        }
        return maxlen;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章