输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
双指针+字典+队列,不难,指针遇到就跳转,并把当前的加入,之前的删掉。注意及时保留最大的子字符串的长度。
import collections
class Solution(object):
def lengthOfLongestSubstring(self, s):
if not s: # 双指针
return 0
deque1 = collections.deque()
maxlength = 0
for i in s:
if i not in deque1: # 字典是1,列表是n
deque1.append(i)
else:
if len(deque1) > maxlength:
maxlength = len(deque1)
deque1.append(i)
val = deque1.popleft()
while val != i:
val = deque1.popleft()
if len(deque1) > maxlength:
= len(deque1)
return maxlength
虽然使用列表判断是否存在某数值的时间复杂度是n,但是可以简洁存储。首先定义一个列表并全部初始化为-1.
在全部都是字母的前提下, i-'a’可以得到距离,把这个距离在列表里对应的位置存储i在字符串中的位置,如果下次遇到了不是-1,说明出现过了。
哈希表+双指针
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
hashmap = {}
head, res = 0, 0
for tail in range(n):
if s[tail] in hashmap:
head = max(hashmap[s[tail]], head)
hashmap[s[tail]] = tail + 1
res = max(res, tail - head + 1)
return res