Skip to content

Commit 7dcd446

Browse files
committed
sliding window
1 parent 91653d8 commit 7dcd446

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Given a string, find the length of the longest substring T that contains at most k distinct characters.
3+
4+
For example, Given s = "eceba" and k = 2,
5+
6+
T is "ece" which its length is 3.
7+
8+
Show Company Tags
9+
Show Tags
10+
Show Similar Problems
11+
"""
12+
from collections import defaultdict
13+
14+
__author__ = 'Daniel'
15+
16+
17+
class Solution(object):
18+
def lengthOfLongestSubstringKDistinct(self, s, k):
19+
"""
20+
Brute force: O(n^2 * n)
21+
22+
Sliding window O(n)
23+
:type s: str
24+
:type k: int
25+
:rtype: int
26+
"""
27+
st = 0 # start
28+
counter = defaultdict(int)
29+
maxa = 0
30+
for idx, val in enumerate(s):
31+
if counter[val] == 0:
32+
k -= 1
33+
34+
counter[val] += 1
35+
while k < 0:
36+
counter[s[st]] -= 1
37+
if counter[s[st]] == 0:
38+
k += 1
39+
st += 1
40+
41+
maxa = max(maxa, idx - st + 1)
42+
43+
return maxa
44+
45+
46+
if __name__ == "__main__":
47+
assert Solution().lengthOfLongestSubstringKDistinct("eceba", 2) == 3

0 commit comments

Comments
 (0)