LeetCode 3. [Python] Longest Substring Without Repeating Characters
原题链接
中等
作者:
徐辰潇
,
2020-07-11 09:06:09
,
所有人可见
,
阅读 552
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
#TC: O(n)
#SC: max(O(n)) n = len(s)
if len(s) == 0:
return 0
left = 0
right = 1
Dict = {}
Dict[s[left]] = 1
res = 1
count = 0
while(right < len(s)):
if s[right] not in Dict:
Dict[s[right]] = 1
if count == 0:
Len = right - left + 1
res = max(res, Len)
else:
Dict[s[right]] += 1
if Dict[s[right]] == 2:
count += 1
while(left < right):
left += 1
Dict[s[left-1]] -= 1
if Dict[s[left-1]] == 0:
del Dict[s[left-1]]
elif Dict[s[left-1]] == 1:
count -= 1
if count == 0:
Len = right - left + 1
break
right += 1
return res