Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
longest-substring-with-at-most-k-distinct-characters.py 1.29 KB
Copy Edit Raw Blame History
# Time: O(n)
# Space: O(1)
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)]
for i, char in enumerate(s):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
while distinct_count > k:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
longest = max(longest, i - start + 1)
return longest
# Time: O(n)
# Space: O(1)
from collections import Counter
class Solution2(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
counter = Counter()
left, max_length = 0, 0
for right, char in enumerate(s):
counter[char] += 1
while len(counter) > k:
counter[s[left]] -= 1
if counter[s[left]] == 0:
del counter[s[left]]
left += 1
max_length = max(max_length, right-left+1)
return max_length
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search