
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Length of Longest Substring with Two Distinct Elements in Python
Suppose we have a string s, we have to find the length of the longest substring that contains at most 2 distinct characters.
So, if the input is like s = "xyzzy", then the output will be 4, as "yzzy" is the longest substring with at most 2 unique characters.
To solve this, we will follow these steps−
start := 0
c := a map
ans := 0
-
for end in range 0 to size of s, do
c[s[end]] := c[s[end]] + 1
-
while size of c > 2, do
-
c[s[start]] := c[s[start]] - 1
-
if c[s[start]] is 0, then
delete c[s[start]]
start := start + 1
-
ans := maximum of ans and (end - start + 1)
return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): from collections import Counter start = 0 c = Counter() ans = 0 for end in range(len(s)): c[s[end]] += 1 while len(c) > 2: c[s[start]] -= 1 if not c[s[start]]: del c[s[start]] start += 1 ans = max(ans, end - start + 1) return ans ob = Solution() s = "xyzzy" print(ob.solve(s))
Input
s = "xyzzy"
Output
4
Advertisements