給定一個(gè)字符串,找出不含有重復(fù)字符的最長(zhǎng)子串的長(zhǎng)度。
示例:
給定 "abcabcbb" ,沒有重復(fù)字符的最長(zhǎng)子串是 "abc" ,那么長(zhǎng)度就是3。
給定 "bbbbb" ,最長(zhǎng)的子串就是 "b" ,長(zhǎng)度是1。
給定 "pwwkew" ,最長(zhǎng)子串是 "wke" ,長(zhǎng)度是3。請(qǐng)注意答案必須是一個(gè)子串,"pwke" 是 子序列 而不是子串。
關(guān)鍵:利用一個(gè)dict記錄每個(gè)字母出現(xiàn)的最后位置,再利用一個(gè)start記錄最靠右的重復(fù)點(diǎn)
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
_max, start, d = 0, 0, {}
for i, _s in enumerate(s):
if _s in d and d[_s] >= start:
start = d[_s] + 1
d[_s] = i
_max = max(_max, i - start + 1)
return _max
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longestLen = 0
i = 0
j = 0
hashMap = {}
for j in range(len(s)):
if s[j] in hashMap.keys():
i = max(hashMap[s[j]], i)
longestLen = max(longestLen, j - i + 1)
hashMap[s[j]] = j + 1
return longestLen