LeetCode 0159. Longest Substring with At Most Two Distinct Characters Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0159. Longest Substring with At Most Two Distinct Characters

Description

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 <= 105
  • s consists of English letters.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: cnt = Counter() ans = j = 0 for i, c in enumerate(s): cnt[c] += 1 while len(cnt) > 2: cnt[s[j]] -= 1 if cnt[s[j]] == 0: cnt.pop(s[j]) j += 1 ans = max(ans, i - j + 1) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !