代码改变世界

[LeetCode] 159. Longest Substring with At Most Two Distinct Characters_Medium tag: Two pointers

2021-08-10 09:21  Johnson_强生仔仔  阅读(31)  评论(0编辑  收藏  举报

Given a string s, return the length of the longest substring that contains at most two distinct characters.

 

Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of English letters.

 

Ideas: 其实跟[LeetCode] 904. Fruit Into Baskets_Medium tag: Two pointers一样,只是换了个马甲而已。

 

Code:

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        visited, d, l, r, n, ans = set(), dict(), 0, 0, len(s), 0
        while r < n:
            c_r = s[r]
            if c_r in visited:
                if r == 0 or s[r] != s[r - 1]:
                    d[c_r] = r
                r += 1
            elif len(visited) < 2:
                visited.add(c_r)
                d[c_r] = r
                r += 1
            elif len(visited) == 2:
                visited = set([c_r, s[r - 1]])
                l = d[s[r - 1]]
                d[c_r] = r
            
            ans = max(r - l, ans)
        return ans