问题描述:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:
输入: s = ""
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
如果暴力不是为了杀戮:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 试了半天,最后想出来一个删除法,即将前面出现的那个字符删掉
s = list(s)
index = 0
exist = []
max_size = 0
cur_size = 0
while len(s) != 0:
si = s[index]
if si not in exist:
exist.append(si)
else:
cur_size = len(exist)
if max_size < cur_size:
max_size = cur_size
exist.clear()
repeat_index = s.index(si)
s = s[repeat_index + 1:]
index = 0
continue
if index+1 < len(s):
index += 1
return max_size