思路一
储存遍历过的字符串,下一个字符串如果遍历过,则找到储存的位置切片O(n^2)
tem=[]
length=0
max=0
for i in s:
if i not in tem:
tem.append(i)
length+=1
if length>max:
max=length
else:
index=tem.index(i)
tem=tem[(index+1):]
tem.append(i)
length=len(tem)
if length>max:
max=length
return max
思路二
1、遍历原字符串
2、已经遍历过的字符放在哈希表中(字典,key是字符,value是index)
3、若新字符已经在hash表中,则取其先出现的index为last(相当于变相对字典切片)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
tem={}
length=0
max=0
last=-1
for index,j in enumerate(s):
if j in tem and tem[j] > last:
length=index-tem[j]
last=tem[j]
tem[j]=index
else:
tem[j]=index
length+=1
max=length if length>max else max
return max
粘自热评
def lengthOfLongestSubstring(self, s: str) -> int:
st = {}
i, ans = 0, 0
for j in range(len(s)):
if s[j] in st:
i = max(st[s[j]], i)
ans = max(ans, j - i + 1)
st[s[j]] = j + 1
return ans;
有点迷
来源:CSDN
作者:wlh156423
链接:https://blog.csdn.net/wlh156423/article/details/104750393