leetcode3_無重複字符的最長子串_滑動窗口

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //初始條件
        if(s.length()==0) return 0;
        int left = 0, right = 0;
        map<char, int> window;
        int match = 0;
        int res = INT_MIN;
        while(right < s.length()) {
            window[s[right]]++;
            if(window[s[right]]==1) match++;
            right++;
            while(right-left!=match) {
                //當有重複時再去移動left++.
                if(s[left]!=s[right-1]) { 
                    match--;
                }
                window[s[left]]--;
                left++;
            }
            //保證所有res比較的都是條件滿足的.
            res = max(res, match);
        }
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章