请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
提示:
s.length <= 40000
注意:本题与主站 3 题相同:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
最先想到的就是直接遍历,max比较
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
i, j = 0, 1
res = 0
while j <= len(s):
if len(s[i:j]) == len(set(s[i:j])):
res = max(res, len(s[i:j]))
else:
i += 1
j += 1
return res
滑动窗口
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
lookup = []
res = 0
# 当前窗口长度
cur_len = 0
for i in range(len(s)):
if s[i] not in lookup:
lookup.append(s[i])
cur_len = len(lookup)
else:
index = lookup.index(s[i])
lookup = lookup[index+1:]
lookup.append(s[i])
cur_len = len(lookup)
# 更新res
res = max(res, cur_len)
return res
while写滑窗
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
i, j = 0, 1
res = 0
while j <= len(s):
if len(s[i:j]) == len(set(s[i:j])):
res = max(res, len(s[i:j]))
else:
i += s[i:j].index(s[j - 1]) + 1 # 这个index求的是s[i:j]的索引
j += 1
return res