题目描述:
最长连续无重复子字符串
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
解题思路:
我们只需要记录,当前字符是否出现在hashmap中,出现的最后的位置是哪里(非当前位置), 还有连续无重复子字符串长度区间的最左边界。
因为只要中间出现过重复序列(abcdda),往后的更新(da)就跟重复序列前面的字符(abcd)毫无关系了。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
left = 0
tab = {} # hashmap
for i, j in enumerate(s):
if j in tab and tab[j] >= left: # 如果j字符在hashmap中出现过,并且j在map中对应的值大于等于区间的左指针,意味着出现重复序列
left = tab[j] + 1 #更新区间的最左边界
tab[j] = i # 更新j字符的最右出现过的位置
ans = max(ans, i - left + 1) #比较最长序列
return ans
网友评论