题目描述:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
第一回:
思路:依次遍历,存在字典中,当有重复的出现,进行长度更新,字典重置。新的位置更新到重复出现的位置。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
length = maxLength = 1
strDic = {}
i = 0
lenS = len(s)
while(lenS):
strDic[s[i]] = i
try:
strDic[s[i + 1]] #判断下一个在字典中是否出现,既重复。
i = strDic[s[i + 1]]/#若出现,新的遍历位置为此重复的字符位置
maxLength = max(maxLength, length)
strDic = {}
length = 1
except KeyError:#字典中不出现,会有KeyError错误。长度增加。
length += 1
except IndexError:
return max(maxLength, length)
i += 1
return maxLength
发现此方法的复杂度,最坏时刻,也是O(N*N)
第二回:
想着,在重复位置逻辑处,进行优化,遍历过程中,将最大的重复位置记录下来,遍历中当有新的重复位置时,更新最大重复位置。更新重复位置值。代码如下:
应用桶存放机制。将字符转换为ACSII值,作为下标,其值为此字符在原始s中的位置。
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
maxLength = 1
strList = [-1] * 300 #长度为300的,值为-1的列表(桶)
maxRepetitionIndex = -1
for i in range(0, len(s)):
if strList[ord(s[i])] > maxRepetitionIndex: #此处比较新的重复位置和最大重复位置
maxRepetitionIndex = strList[ord(s[i])]
strList[ord(s[i])] = i #列表更新
maxLength = max(maxLength, i - maxRepetitionIndex)
return maxLength
复杂度为O(N),但是需要开辟一定长度的list,(长度为字符ACSII的范围,大于也可以。)