LeetCode 159 Longest Substring with At Most Two Distinct Characters

LeetCode 159 Longest Substring with At Most Two Distinct Characters Problem

Download Code
class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """
        i, j, maxLen = 0, -1, 0
        # i for start, k for end, j for latest pos contains different character from k
        for k in range(1, len(s)):
            if s[k] == s[k - 1]:
                continue
            if j >= 0 and s[j] != s[k]:
                maxLen = max(k - i, maxLen)
                # update i
                i = j + 1
            # update
            j = k - 1
        return max(len(s) - i, maxLen)
Download Longest Substring with At Most Two Distinct Characters.py

List of all Longest Substring with At Most Two Distinct Characters problems

Leetcode 159 Longest Substring with At Most Two Distinct Characters problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.