题目原文:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
代码:
class Solution:
#寻找在已有的list中最后一个重复的字符的位置
def Str_last_index(self,s:list,alpha) -> int:
index = -1
str_len = -1 * len(s)
while index >= str_len:
if s[index] == alpha:
return index + len(s)
else:
index = index - 1
return -1 #这里的return -1其实没啥用
def lengthOfLongestSubstring(self, s: str) -> int:
if s == "":
return 0
Sub_list = list()
Last_list = list()
index = 1
Sub_list.append(s[0])
Last_list = Sub_list[::]
while index < len(s):
if s[index] in Sub_list:
Last_index = self.Str_last_index(Sub_list,s[index]) + 1 #找到最后一个重复字符的后面一个位置
Sub_list = Sub_list[Last_index : index] #复制从最有一个重复字符后面一个位置到现在的位置所有的元素
Sub_list.append(s[index])
index = index + 1
else:
Sub_list.append(s[index])
index = index + 1
if len(Last_list) < len(Sub_list):
Last_list = Sub_list[::] #复制list
return len(Last_list)
这道题错的还是有点惨的(毕竟我是菜逼),代码是提交了9次才通过运行的。代码的时间复杂度分析应该是O(n)