题目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
思路
用两个指针标记起始和结束位置,并将起始和结束之间的字符串保存在一个map中。结束位置向左移动,没有重复的就向map中添加,并计算最大长度,直到出现重复字符。然后起始位置向左移动到重复字符的下一个,并在map中删除期间走过的所有字符。这个过程一定是长度减小的所以不用计算maxLength。走完即可。
解法
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
map1 = {}
head = 0
maxLength = 0
for i in range(len(s)):
if map1.has_key(s[i]):
headNew = int(map1.get(s[i]))
for j in xrange(head,headNew):
del map1[s[j]]
head = headNew + 1
map1[s[i]] = str(i)
else:
map1[s[i]] = str(i)
if i-head+1>maxLength:
maxLength = i-head+1
return maxLength
问题
暂时不知道是什么地方导致了比较多的耗时。该时间复杂度理论上是O(n),但结果只打败了10%的人。如果有人知道更好的方法,或者我的代码哪里写的耗时比较大,请留言,谢谢各位大神。