1.暴力枚举解法:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
elif len(s) == len(list(set(s))):
return len(s)
elif len(list(set(s)))==1:
return 1
else:
l = []
for i in range(len(s)):
index_i = s[i+1:].index(s[i])+i+1 if s[i] in s[i+1:] else len(s)
end_i = i + max(l) if len(l) > 0 else i
for j in range(index_i,end_i,-1):
sub = s[i:j]
if len(list(set(sub))) == len(sub):
l.append(len(sub))
break
return max(l)
#暴力解法
暴力枚举解法,很容易出现超出时间限制得问题,需要想许多的限制条件。例如枚举时,只寻找长度比当前结果中最大长度大的子序列,预先检查是否是否为相同字符的字符串等。
2.窗移动方法:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
l = []
res = []
for i in s:
if i not in l:
l.append(i)
else:
res.append(len(l))
index_i = l.index(i)
l = l[index_i+1:]
l.append(i)
res.append(len(l))
return max(res) if res !=[] else 0
3.两种方法的结果比较