劍指Offer(Python多種思路實現):最長不含重複字符的子字符串
面試48題:
題目:最長不含重複字符的子字符串
題:請從字符串中找出一個最長的不包含重複字符的子字符串,計算該最長字符串的長度。假設字符串中只包含‘a’-‘z’的字符。例如,在字符串“arabcacfr”中,最長的不含重複字符的子字符串是“acfr”,長度爲4。
解題思路一:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start=0
maxLength=0
usedChar={}
for i in range(len(s)):
if s[i] in usedChar and start<=usedChar[s[i]]:
start=usedChar[s[i]]+1
else:
maxLength=max(maxLength,i-start+1)
usedChar[s[i]]=i
return maxLength
解題思路二:
def lengthOfLongestSubstring(self, s):
ans = start = 0
pos = {} # last index of element
for end, c in enumerate(s):
if c in pos:
start = max(start, pos[c]+1)
pos[c] = end
ans = max(ans, end-start+1)
return ans