3. 无重复字符的最长子串
注意这里是 “子串” 而非 “子序列” (即必须是连续的字符序列)
(1)方法一:暴力
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
if length == 0: # 两种特殊短串
return 0
if length == 1:
return 1
max_string = s[0] # 初始化最长子串
for i in range(length-1): # 控制起始字符
if len(max_string) > length - i:
# 如果剩余字符量已经不可能超过现有最长子串
break
now = s[i]
for j in range(i+1, len(s)): # 不断向后增加一个字符
if s[j] not in now:
now += s[j]
else:
# 如果不再满足连续子串的要求,就跳出,换下一个起始字符
break
if len(now) > len(max_string):
max_string = now
return len(max_string)
执行用时:488 ms, 在所有 Python3 提交中击败了16.41%的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了5.88%的用户
[思路]:两层循环
(2)方法二:技巧
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
# 两种特殊短串
if length == 0:
return 0
if length == 1:
return 1
now_list = []
length_list = []
for c in s:
# 判定:如果出现重复,则cut掉重复字符前的子串,消除重复
# 并将先前的长度存入length_list
if c in now_list:
length_list.append(len(now_list))
now_list = now_list[now_list.index(c)+1:]
# 如果是不重复的字符,则直接加入now_list
# 重复字符在判定修改结束后,也要加入Now_list
now_list.append(c)
# 保存一下最后一步now_list的长度
length_list.append(len(now_list))
return max(length_list)
执行用时:60 ms, 在所有 Python3 提交中击败了96.93%的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.88%的用户
[思路]:在不重复的情况下不断加入新字符;若碰到重复字符B,则保存现有长度,然后 cut 掉重复字符A及其前的所有字符,使得重复消去。
最后从长度列表中选出最大的。