滑动窗口问题
3.找到无重复子串最大长度。medium
自己思想:
外层循环:逐个字符作为子串开头
内层循环:逐个增加当前子串长度,若出现重复,停止跳出循环,并记录当前子串长度。
循环结束
循环结束
取子串长度最大的长度返回。
答案版本1思想:采用Python的set,可以知道无重复子串的可能的最大长度,把可能的最大长度作为滑动窗口的初始大小,并在搜索中调节窗口大小直到找到最大无重复子串。参考代码如下:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
len_s = len(s)
if len_s == 0:
return 0
set_s = set(s)
# get the max_size of sild window
max_len = len(set_s)
max_sub_str = ""
while max_len:
if max_len == 1:
return 1
i = 0
while i + max_len <= len_s:
sub_s = s[i:i + max_len]
set_sub = set(sub_s)
# if there is no repeat in sub string
if len(set_sub) == len(sub_s):
max_sub_str = sub_s
return(len(list(max_sub_str)))
i = i + 1
# adjust the size of window
max_len = max_len - 1
答案2版本(复杂度O(n)):
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}
for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1)
usedChar[s[i]] = i
return maxLength