面试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 maxLengthif __name__=="__main__": print(Solution().lengthOfLongestSubstring('arabcacfr')) print(Solution().lengthOfLongestSubstring('abcabcbb')) print(Solution().lengthOfLongestSubstring('bbbbb')) print(Solution().lengthOfLongestSubstring('pwwkew'))