Given a string, find the length of the longest substring without repeating characters.
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 3.
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
这道题乍看还是比较简单,但是有很多细节在里面,先给一下实现代码
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxlen = 0
start = 0
dt = {}
for i,c in enumerate(s):
if c in dt:
start = max(start,dt[c]+1)
maxlen = max(maxlen,i-start+1)
dt[c] = i
return maxlen
首先关键就在于:
start = max(start,dt[c]+1)
笔者之前是:
start = dt[c]+1
对比两者的差别,错误样本是:
abba
0,1,2,3
当判断第二个a时,start此时就在2的位置,如果采用笔者之前的,那么start其实在1,但是bb也就是中间已经重复了,换句话说:
......a....c.............c.....a............b................
......a....c.............c.....a............b................
当我们在第二个a的位置时候,原本来说是两个a的之间的长度,但有可能其中间有部分已经重复,例如红色的部分,所以这样做是错的,当使用了
start = max(start,dt[c]+1)
此时start应该在第一个C的下一个位置,所以
i-start后应该是绿色部分,符合我们想要的