题目:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解法一:用字典记录字母是否已存在
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max = 0
res = list(s)
for x in range(len(res)):
n = 1
dict = {}
dict[res[x]] = 1
for y in range(x+1, len(res)):
if res[y] in dict:
break
else:
dict[res[y]] = 1
n = n+1
if n > max:
max = n
return max
耗时504ms
解法二:用标记位记录起始位置,一旦出现重复位(如第2、5位上出现的字符重复),则将起始位记为第一次记录位置(第2位)的下一位
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = 0
dict={}
max = 0
for i in range(len(s)):
if s[i] not in dict:
dict[s[i]] = i
else:
if dict[s[i]] + 1 > start:
start = dict[s[i]] + 1
dict[s[i]] = i
if i - start + 1 > max:
max = i - start + 1
return max
耗时64ms