Q:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b"
,所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是"wke"
,所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke"
是一个子序列,不是子串。
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/
思路:双指针 惨不忍睹
代码:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
if len(s) == len(list(set(list(s)))):
return len(s)
slow = 0
fast = 1
max_ = 0
while (fast < len(s)):
if s[fast] not in s[slow:fast]:
fast += 1
else:
if fast-slow > max_:
max_ = fast-slow-1
slow += 1
fast = slow
if fast - slow > max_:
max_ = fast - slow - 1
return max_+1
AC优秀代码:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
list_ = []
max_ = 0
for i in s:
if i in list_:
del list_[0:list_.index(i) + 1]
list_.append(i)
else:
list_.append(i)
if len(list_) > max_:
max_ = len(list_)
return max_