3.无重复字符的最长子串
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
示例 4:
输入: s = “”
输出: 0
解题思路
这道题的思路为双指针法。 利用一个字典以及一个count来检测是否有重复字符。当存在重复字符时,count+1,然后start这个指针后移直到count变为1(当start指到重复字符才会count -1)。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
from collections import defaultdict
start,end = 0,0
m = 0
count = 0
d = defaultdict(int)
if len(s)==0:
return 0
while end < len(s):
if d[s[end]] > 0:
count+=1
d[s[end]] += 1
end += 1
while count:
if d[s[start]] > 1:
count-=1
d[s[start]] -= 1
start += 1
m = max(m,end - start)
return m