159 - Longest Substring with At Most Two Distinct Characters

解法一 - Sliding Window

這題在概念上跟 # 904 一模一樣,只是敘述方法不同,所以直接上程式碼:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int windowStart = 0, maxLength = 0;
        unordered_map<char, int> table;

        for (int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
            table[s[windowEnd]]++;

            while (table.size() > 2) {
                if (--table[s[windowStart]] == 0) {
                    table.erase(s[windowStart]);
                }
                windowStart++;
            }

            maxLength = max(maxLength, windowEnd-windowStart+1);
        }

        return maxLength;
    }
};

results matching ""

    No results matching ""