给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
思路:
1.滑动窗口:设置 l o w low low, h i g h high high指针,代表滑动窗口起点和终点。设置列表存储窗口内的元素。遍历字符串,若在此元素不在窗口内则添加, h i g h = h i g h + 1 high=high+1 high=high+1,若在窗口内则向右移动窗口, l o w = l o w + 1 low=low+1 low=low+1,去除列表最左元素。继续从失效处遍历的字符串。时间复杂度 O ( n 2 ) O(n^2) O(n2)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res=[]
if not s:
return 0
l=len(s)
low=0
high=0
i=0
max=1
while i<l:
if s[i] not in res:
res.append(s[i])
high+=1
else:
i=i-1
res.pop(0)
low+=1
if high-low>max:
max=high-low
i+=1
return max
改进
1.时间主要消耗在列表查找中,Python中查找效率set>dict>list,
set和dict都有做哈希,不出现冲突的话查询时间复杂度O(1)。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res=set()
if not s:
return 0
l=len(s)
low=0
high=0
i=0
max=1
while i<l:
if s[i] not in res:
res.add(s[i])
high+=1
else:
i=i-1
res.remove(s[low])
low+=1
if high-low>max:
max=high-low
i+=1
return max