[LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有兩個不同字符的最長子串


 

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.

 

這道題給我們一個字符串,讓求最多有兩個不同字符的最長子串。那么首先想到的是用 HashMap 來做,HashMap 記錄每個字符的出現次數,然后如果 HashMap 中的映射數量超過兩個的時候,這里需要刪掉一個映射,比如此時 HashMap 中e有2個,c有1個,此時把b也存入了 HashMap,那么就有三對映射了,這時 left 是0,先從e開始,映射值減1,此時e還有1個,不刪除,left 自增1。這時 HashMap 里還有三對映射,此時 left 是1,那么到c了,映射值減1,此時e映射為0,將e從 HashMap 中刪除,left 自增1,然后更新結果為 i - left + 1,以此類推直至遍歷完整個字符串,參見代碼如下:

 

解法一:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int res = 0, left = 0;
        unordered_map<char, int> m;
        for (int i = 0; i < s.size(); ++i) {
            ++m[s[i]];
            while (m.size() > 2) {
                if (--m[s[left]] == 0) m.erase(s[left]);
                ++left;
            }
            res = max(res, i - left + 1);
        }
        return res;
    }
};

 

我們除了用 HashMap 來映射字符出現的個數,還可以映射每個字符最新的坐標,比如題目中的例子 "eceba",遇到第一個e,映射其坐標0,遇到c,映射其坐標1,遇到第二個e時,映射其坐標2,當遇到b時,映射其坐標3,每次都判斷當前 HashMap 中的映射數,如果大於2的時候,那么需要刪掉一個映射,還是從 left=0 時開始向右找,看每個字符在 HashMap 中的映射值是否等於當前坐標 left,比如第一個e,HashMap 此時映射值為2,不等於 left 的0,那么 left 自增1,遇到c的時候,HashMap 中c的映射值是1,和此時的 left 相同,那么我們把c刪掉,left 自增1,再更新結果,以此類推直至遍歷完整個字符串,參見代碼如下:

 

解法二:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int res = 0, left = 0;
        unordered_map<char, int> m;
        for (int i = 0; i < s.size(); ++i) {
            m[s[i]] = i;
            while (m.size() > 2) {
                if (m[s[left]] == left) m.erase(s[left]);
                ++left;
            }
            res = max(res, i - left + 1);
        }
        return res;
    }
};

 

后來又在網上看到了一種解法,這種解法是維護一個 sliding window,指針 left 指向起始位置,right 指向 window 的最后一個位置,用於定位 left 的下一個跳轉位置,思路如下:

1. 若當前字符和前一個字符相同,繼續循環。

2. 若不同,看當前字符和 right 指的字符是否相同

    (1) 若相同,left 不變,右邊跳到 i - 1

    (2) 若不同,更新結果,left 變為 right+1,right 變為 i - 1

最后需要注意在循環結束后,還要比較結果 res 和 s.size() - left 的大小,返回大的,這是由於如果字符串是 "ecebaaa",那么當 left=3 時,i=5,6 的時候,都是繼續循環,當i加到7時,跳出了循環,而此時正確答案應為 "baaa" 這4個字符,而我們的結果 res 只更新到了 "ece" 這3個字符,所以最后要判斷 s.size() - left 和結果 res 的大小。

另外需要說明的是這種解法僅適用於於不同字符數為2個的情況,如果為k個的話,還是需要用上面兩種解法。

 

解法三:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int left = 0, right = -1, res = 0;
        for (int i = 1; i < s.size(); ++i) {
            if (s[i] == s[i - 1]) continue;
            if (right >= 0 && s[right] != s[i]) {
                res = max(res, i - left);
                left = right + 1;
            }
            right = i - 1;
        }
        return max(s.size() - left, res);
    }
};

 

還有一種不使用 HashMap 的解法,是在做 Fruit Into Baskets 這道題的時候在論壇上看到的,其實這兩道題除了背景設定之外沒有任何的區別,代碼基本上都可以拷來直接用的。這里使用若干的變量,其中 cur 為當前最長子串的長度,first 和 second 為當前候選子串中的兩個不同的字符,cntLast 為 second 字符的連續長度。遍歷所有字符,假如遇到的字符是 first 和 second 中的任意一個,那么 cur 可以自增1,否則 cntLast 自增1,因為若是新字符的話,默認已經將 first 字符淘汰了,此時候選字符串由 second 字符和這個新字符構成,所以當前長度是 cntLast+1。然后再來更新 cntLast,假如當前字符等於 second 的話,cntLast 自增1,否則均重置為1,因為 cntLast 統計的就是 second 字符的連續長度。然后再來判斷若當前字符不等於 second,則此時 first 賦值為 second, second 賦值為新字符。最后不要忘了用 cur 來更新結果 res,參見代碼如下:

 

解法四:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int res = 0, cur = 0, cntLast = 0;
        char first, second;
        for (char c : s) {
            cur = (c == first || c == second) ? cur + 1 : cntLast + 1;
            cntLast = (c == second) ? cntLast + 1 : 1;
            if (c != second) {
                first = second; second = c;
            }
            res = max(res, cur);
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/159

 

類似題目:

Fruit Into Baskets

Longest Substring Without Repeating Characters

Sliding Window Maximum

Longest Substring with At Most K Distinct Characters

Subarrays with K Different Integers

 

參考資料:

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49759/Share-my-c%2B%2B-solution

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49687/Clean-11-lines-AC-answer-O(1)-space-O(n)-time.

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49682/Simple-O(n)-java-solution-easily-extend-to-k-characters

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49708/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM