Python语言,leetcode题库刷题记录 (三) Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
我的python代码:
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ char_array = [] res = 0 temp = 0 for i in range(0,95): char_array.append(0) arr = list(s) char_array_bak = char_array[:] for index in range(len(arr)): if char_array_bak[ord(arr[index])-32]==0: char_array_bak[ord(arr[index])-32] = 1 temp += 1 if temp>res: res = temp else: char_array_bak = char_array[:] for index2 in range(index,0,-1): if arr[index2-1]==arr[index]: for k in range(index2,index+1): char_array_bak[ord(arr[k])-32] = 1 temp = index - index2 + 1 break return res
上段代码很长很蠢,没什么好介绍的,为了记录自己以前的僵化思想在此记录
点开提示之后结合别人的方法使用词典,下面是新的代码
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ used_char = {} res = begin = 0 for i in range(0,len(s)): if used_char.has_key(s[i]) and begin <= used_char[s[i]]: begin = used_char[s[i]]+1 else: res = max(res, i-begin+1) used_char[s[i]] = i return res
上面的思路是记录每一串不重复子串开始的位置,直到结束时计算其长度,与之前出现过的最长不重复子串比长度。时间复杂度为O(n)

浙公网安备 33010602011771号