class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)==0:
return 0
if len(s)==1:
return 1
else:
result=''
result+=s[0]
max_length=[]
for i in range(len(s)-1):
for j in range(i+1,len(s)):
if s[j] not in result:
result+=s[j]
else:
break
length=len(result)
max_length.append(length)
result=''
result+=s[i+1]
return max(max_length)
写得够烂的哈哈
知识点:
字符串没有append的概念,如果要合并在一起用+。
优化代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
#" "
#Expected Output:1
#max=i-start=0-start=1 start=-1
#d={'a':0,'b':1,...} value=index
start=-1
max=0
d={}
for i in range(len(s)):
if s[i] in d and d[s[i]]>start:
start=d[s[i]]
d[s[i]]=i#重新赋值
else:#s[i] not in d
d[s[i]]=i#写在dict里面
if i-start>max:
max=i-start
return max
分析 if s[i] in d and d[s[i]]>start:中的 d[s[i]]>start
测试代码:s="tmmzuxt"
(1)有d[s[i]]>start:
(2)没有d[s[i]]>start: