题目:
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.
1. 笨拙但易懂的方法
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
MaxLen = 0 #需要返回的最大长度
subStr = []
subStr.append(list()) #add an list(), 每一组不重复的都存成一个list
j = 0
tmpLen = 0 #记录当前list的最大长度
for num in s:
if num not in subStr[j]: # 如果当前list里面没有该字母,加上该字母
subStr[j].append(num) # add the character
tmpLen = len(subStr[j])
else:
Index = subStr[j].index(num) # 查找当前num与第几个相同
#print (Index)
j = j+1 #已经与前面的有重复了,那么需要生成新的substring
subStr.append(list()) #增加list()
if (int(Index+1) == len(subStr[j-1])):#恰好等于最后一个数,也就是连着两个重复的
#print ("the same with the last one")
subStr[j].append(num)# 把最后那个加上
if (subStr[j-1][Index+1:]):#如果不是等于最后一个数,那把从重复的那个数开始的后面一些数都加入到新的list中
for k in range(Index+1 , len(subStr[j-1])):
subStr[j].append(subStr[j-1][k])# 复制后面几个到新的list中
subStr[j].append(num)#以及append当前的num
if (MaxLen < tmpLen):
MaxLen = tmpLen
return MaxLen
2. 简练代码
参考 https://github.com/illuz/leetcode
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
left = 0
d = {} #创建字典,维护每个出现的字母的最大序号
for i, ch in enumerate(s):
if ch in d and d[ch] >= left:
left = d[ch] + 1
d[ch] = i #某个字母对应的最大的序号
res = max(res, i - left + 1) #(i-left+1)为到目前位置,本小节的长度
return res