剑指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