Longest Substring Without Repeating Characters
考虑不重复的字串,主要的考点在于:
- 是否了解指针构建字串移动窗口
- 当出现新的重复值时怎么改变窗口left指针
其实自己一开始的想法是想着能不能记录下每次出现的位置,然后用集合取交集的思想得到一个区域差值。最后发现不可以,因为对于两端的情况很难解决。
参考网上的解法,其实只要知道用双指针来构建这个字串的滑动窗口,其实就差不多知道怎么做了。其外一个坑的地方就在于这个窗口left指针如何进行移动,不过自己画几个用例也就可以知道,如果不在滑动窗口内没事,如果在窗口内那么left指针要移动到上一个重复字符的下一个位置。
自己的代码
from collections import defaultdict
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)<1:
return 0
len_s=len(s)
f=0
end=0
max_interval=0
res={}
for i in range(len_s):
temp=s[i]
if temp in res and res[temp]>=f:
f=res[temp]+1
res[temp]=i
end+=1
temp_interval=end-f
max_interval=max_interval if max_interval>temp_interval else temp_interval
return max_interval
leetcode上最快的代码:
其实改进的点也容易理解:
主要在于原代码的合并,有些过程或者变量重复处理,去掉就能变快。
- 实际上需要改变的只是一个left指针,right指针是跟i一样的
- 采用enumerate(),自己还在傻乎乎的取len再range
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
dic = {}
ans = 0
lastDup = 0
for i, ch in enumerate(s):
if ch in dic and lastDup <= dic[ch]:
# print i, lastDup
lastDup = dic[ch]+1
else:
# print ch, i
ans = max(ans, i-lastDup+1)
dic[ch] = i
return ans