原题链接:点击打开链接
题目:
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.
解题思路:
刚开始的时候用一个字典配合一个列表做,用列表保存每轮找到的最长的string,当遇到重复的字符时,到字典中查找重复字符先前出现的位置,之后再将curpoint指针指到那个字符的后面一位重新开始。举个栗子,比如“dvdf”这个字符串,当顺序读到第二次出现的d是,字典中内容为{d:0,v:1},可以查到之前出现的d的位置为0,于是将curpoint置为1,即从v开始重新查找。
但是在提交时发现,有一个用例测试不通过,原因是运行超时。分析上面的做法可知上面描述的算法中做了很多重复的工作。进一步改进的做法是不再使用列表,而只用一个字典做,每次的删除工作直接在字典上进行,可以有效避免重复工作,
AC代码如下:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
curpoint = 0
llen = 0
popkey_list = []
detect_repeat = {}
while curpoint < len(s):
if s[curpoint] in detect_repeat:
if len(detect_repeat.keys()) > llen:
llen = len(detect_repeat.keys())
for key,value in detect_repeat.iteritems():
if value <= detect_repeat[s[curpoint]]:
popkey_list.append(key)
for key in popkey_list:
detect_repeat.pop(key)
popkey_list = []
detect_repeat[s[curpoint]] = curpoint
curpoint += 1
if len(detect_repeat.keys()) > llen:
llen = len(detect_repeat.keys())
return llen