Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
思路:
看到这个“不重复”我基本就已经想着要用哈希了,初步思路是想将每个字符和位置对应成字典,如果出现重复字母,就重置字典,并将重复字母索引+1,开始新一轮索引。但这样遇到abcabcbb这种字符串的话,要循环太多遍,时间成本太高。后来想出来一种只需要循环一遍就可以的算法,重点是记录重复字母的标签,而不是清空字典,想明白这个之后就好写了。
代码如下:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
start =long = 0
for i in range(len(s)):
#这里解释一下为什么要start<= d[s[i]],因为对于字符串tmmzuxt来说,当start指向第二个m,i已经到最后一个字母t的时候,这时候就不能将start重置为0+1,因为此时start已经在2了。
if s[i] in d.keys() and start <= d[s[i]]:
start = d[s[i]]+1
else:
long = max(long,i-start+1)
d[s[i]]=i
return long