Skip to content

Commit 3eaa882

Browse files
authored
Create 340._Longest_Substring_with_At_Most_K_Distinct_Characters.md
1 parent fdf8205 commit 3eaa882

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# 340. Longest Substring with At Most K Distinct Characters
2+
3+
**<font color=red>难度: Hard</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/description/
10+
11+
> 内容描述
12+
13+
```
14+
15+
Given a string, find the length of the longest substring T that contains at most k distinct characters.
16+
17+
Example 1:
18+
19+
Input: s = "eceba", k = 2
20+
Output: 3
21+
Explanation: T is "ece" which its length is 3.
22+
Example 2:
23+
24+
Input: s = "aa", k = 1
25+
Output: 2
26+
Explanation: T is "aa" which its length is 2.
27+
```
28+
29+
## 解题方案
30+
31+
> 思路 1
32+
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******
33+
34+
35+
思路见第159题
36+
37+
```python
38+
class Solution(object):
39+
def lengthOfLongestSubstringKDistinct(self, s, k):
40+
"""
41+
:type s: str
42+
:type k: int
43+
:rtype: int
44+
"""
45+
maps = {}
46+
begin, end, counter, length = 0, 0, 0, 0
47+
while end < len(s):
48+
maps[s[end]] = maps.get(s[end], 0) + 1
49+
if maps[s[end]] == 1:
50+
counter += 1
51+
end += 1 # end 永远指向下一个待处理的字符
52+
while counter > k:
53+
maps[s[begin]] -= 1
54+
if maps[s[begin]] == 0:
55+
counter -= 1
56+
begin += 1
57+
length = max(length, end - begin) # 因此这里是```end - begin```而不是```end - begin + 1```
58+
return length
59+
```

0 commit comments

Comments
 (0)