题目详情:
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
题解:
1.暴力求解:
def lengthOfLongestSubstring(s):
length = len(s)
num = []
# num[i]存储s从下标是i开始的最长无重复字符的最长子串的长度
n = len(set(s))
# n代表了该字符串不含有重复的字符的最长子串的长度,num[i]不可能超过n
mx = 1
for i in range(length-1):
num.append(1)
for t in range(i+1, length):
flag = True
for j in range(i, t):
if s[t] == s[j]:
flag = False
break
if flag:
num[i] += 1
else:
break
if num[i] == n:
#利用num[i]不可能超过n来提前结束循环,可以节约时间,不然leetcode时间超时
return n
for res in num:
if mx < res:
mx = res
if length == 0:
mx = 0
return mx
2.滑动窗口:
def lengthOfLongestSubstring(s):
lt = len(s)
start = 0
end = 1
mx = 0 # 记录t的最大值
t = 0 # 在每次循环中都会变化
n = len(set(s)) # 加入小心思,有概率让循环提前结束
while start<lt and end <lt:
if s[end] in s[start:end]:
start += 1
t -= 1
else:
end += 1
t += 1
if t > mx:
mx = t
if mx == n:
return mx
return mx