思路
一、队列
遍历字符串,如果队列中没有该字符,则将该字符入队;若存在,则出队,直至队列中没有该字符,再入队。记录下队列最长的时候,即为答案。
# python3
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
ans = list()
maxlen = 0
for n in s:
if n not in ans:
ans.append(n)
else:
while n in ans:
ans.pop(0)
ans.append(n)
maxlen = max(maxlen, len(ans))
return maxlen
执行用时:
88 ms, 在所有 Python3 提交中击败了39.21%的用户
内存消耗:
15 MB, 在所有 Python3 提交中击败了35.44%的用户
时间复杂度:O(n^2)
效率一般
二、滑动窗口+哈希表
- 遍历字符串s,用哈希表记录每个字符的下标index,key为字符,value是该字符的下标。
- left用于记录字符串的最左侧字符的下标,maxLen用于记录子串的最大长度
- 如果当前遍历到的字符已在哈希表中存在,说明是个重复字符,子串的左侧下标应该从该字符前一次出现的下标的下一个位置开始。也就是说要更新left为该字符前一次出现时的下标,但是因为前一个字符可能已不在子串中,比如“cwkewc”字符串,当遍历到第二个w时,会更新left的下标为第一个w的下标,这样left的下标就会比第一个c大,所以当遍历到第二个c时,就不需要更新left。
所以left更新的条件是left比该字符前一次出现时的下标要小,即 left < [s[index]] - 子串的长度即为当前索引 i - 左侧索引 left + 1, maxLen取子串长度的最大值
代码
# python3
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
ans = {}
left = -1
maxlen = 0
for index in range(len(s)):
if s[index] in ans and ans[s[index]] > left:
left = ans[s[index]]
ans[s[index]] = index
else:
ans[s[index]] = index
maxlen = max(maxlen, index - left)
return maxlen
时间复杂度:O(n)
执行用时:
44 ms, 在所有 Python3 提交中击败了99.84%的用户
内存消耗:
14.8 MB, 在所有 Python3 提交中击败了69.95%的用户