题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
解题思路:
1、使用起始、结束两个标记,移动结束标记并字典记录每一个字符在当前子串中第一次出现的位置;使用res变量记录当前最大子串长度,初始值为0;
2、遍历字符串判断字符是否在子串中出现过,如果出现过,记录当前子串长度并更新res值后,删除字典中重复字符前的字符记录;并移动起始标记;
3、如果字符未出现过,则继续移动结束标记;
4、结束标记已到字符串结尾,再次更新res值。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return int整型
#
class Solution:
def popItem(self,s: str,start:int,end:int,nums:dict):
for i in range(start,end+1):
nums.pop(s[i])
def getRes(self,start,end,res):
if end - start > res:
res = end - start
return res
def lengthOfLongestSubstring(self , s: str) -> int:
start = 0
end = 0
length = len(s)
nums = dict()
res = 0
while end < length:
if s[end] in nums:
res = self.getRes(start,end,res)
temp_start = nums[s[end]] + 1
self.popItem(s,start,nums[s[end]],nums)
start = temp_start
else:
nums[s[end]] = end
end += 1
if end == length:
res = self.getRes(start,end,res)
return res
查看8道真题和解析