3. Longest Substring Without Repeating Characters
![17368230-fda31f4427865191.png](https://i-blog.csdnimg.cn/blog_migrate/0600c1bd9fd5cd1e7abef2c8e6aded74.webp?x-image-process=image/format,png)
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
太菜了,这样复杂度太高了,【来也】面试问到,然后让改进。
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