3. Longest Substring Without Repeating Characters
滑动窗口,start开始,每加入一个字符,查找窗口内也没有当前字符,如果有,就更新start
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
left = res = 0
for i in range(len(s)):
index = s[left:i].find(s[i])
if index >= 0:
left = left + index + 1
res = max(res, i - left + 1)
return res
太菜了,这样复杂度太高了,【来也】面试问到,然后让改进。空间换时间,用一个dic记录每个字母最近出现过的index,当index在窗口内,需要更新start,同时更新dic。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) <= 1:
return len(s)
maxlen = 0
mydic = {}
left = 0
for i in range(len(s)):
if s[i] in mydic and mydic[s[i]] >= left:
left = mydic[s[i]] + 1
mydic[s[i]] = i
maxlen = max(maxlen, i - left + 1)
return maxlen
还有就是需要搞清楚,index会报错,find不会报错,会返回-1