3. Longest Substring Without Repeating Characters
题目描述
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 subsequenceand not a substring.
分析
只需要返回最大长度值,所以只需要一个int型变量保存返回结果;
定义两个指针,记录当前找到的无重复子串的起始和终止位置(终止即当前遍历到的索引位置)。
完整代码
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxlen=start=0
used={} #保存已遍历的字符和最近出现的位置
for i,c in enumerate(s):
if c in used and start<=used[c]: #若当前字符之前出现过,并且在start之后
start=used[c]+1 #更新起点
else:
maxlen=max(maxlen,i-start+1) #更新最大长度
used[c]=i #更新字符出现的位置
return maxlen
第二次做:出错:“dvdf”的答案为2
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
fir = sec = 0
ans = 0
le = len(s)
while fir<le:
if sec < le:
c = s[sec]
if c in d and fir<=d[c]:
fir = d[c] + 1
d[c] = sec
ans = max(sec - fir+1, ans)
sec = sec + 1
# 当到达右边界但未到达左边界时,左边界右移继续循环
else:
sec = fir = fir+1
return ans
tips:
1. 当右指针到达右边界时,左指针需要右移,直到左右都到达右边界为止。
2. 更新左指针时,必须以重复元素之前的位置开始右移,而不是以最初的左指针位置开始右移。
出错:if c in d and fir<=d[c]:
必须保证fir是在原始d[c]的右边,才可以将fir更新为d[c]+1,否则,只需要更新d[c]的值即可。
需要先在滑动窗口内去掉这个已经出现过的字符了,去掉的方法并不需要将左边界left一位一位向右遍历查找,由于我们的HashMap已经保存了该重复字符最后出现的位置,所以直接移动left指针就可以了。
3. 判断是否存在问题,使用hashmap,因为hash的速度最快。