无重复字符的最长字符串
题目:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
法一:
def lengthOfLongestSubstring(s): listi = [] if len(s) in [0,1]: return len(s) else: for i in range(len(s)): j = i while j < len(s)-1: j = j + 1 r = s[i:j] if s[j] in r: maxlen = len(r) listi.append(maxlen) break else: maxlen = len(r)+1 listi.append(maxlen) return max(listi) if __name__ == '__main__': s = "" print(lengthOfLongestSubstring(s))
思路: 无脑遍历,( 0 or 1)不好用,不知道为什么
给变量起名字时不要起list,max和函数名一致的,否则报错
法二:
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ start = maxLength = 0 usedChar = {} for index, char in enumerate(s): if char in usedChar and start <= usedChar[char]: start = usedChar[char] + 1 # 将值加1 else: maxLength = max(maxLength, index - start + 1) usedChar[char] = index return maxLength if __name__ == '__main__': s = 'abcdecb' print(lengthOfLongestSubstring(s))
思路:方法比较难
不断判断新的元素是否是已经存在于usedChar字典中,若存在,则将start指向已经存在的位置,继续遍历,否则判断长度,求max