leecode 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
方法一:利用字典当中的键值不能重复的特点,当出现字典的长度小于循环的次数时,一定有重复的字符出现,此时记录字符长度。在将字符串去掉最左边的字符,开始下一次查询。
class Solution:
def lengthOfLongestSubstring(self, s):
lenth=1
lenth_max=0
while len(s)!=0:
dict1={}
lenth = 1
for num1,letter in enumerate(s):
dict1[letter]=num1
if len(dict1)<lenth:
break
lenth+=1
if lenth_max<lenth-1:
lenth_max=lenth-1
s=s[1:]
print(lenth_max)
return lenth_max
但是这种方法不太好,有些拐弯抹角,不直接
方法二:滑动窗口的经典方法
class Solution:
def lengthOfLongestSubstring(self, s):
window=[]
lenth_max=0
for n in s:
if n not in window:
window.append(n)
else:
window.append(n)
window=window[window.index(n)+1:]
lenth_max=max(len(window),lenth_max)
print(lenth_max)
return lenth_max
效果还行
但是我们发现还有改进的空间,在查找字符是否在字符串的过程中,我们可以利用字典(哈希表)来实现快速查找,从而加快速度
方法三:在二的基础上稍作改进,使用字典来提高查找效率:
class Solution:
def lengthOfLongestSubstring(self, s):
dict1={}
lenth_max=0
i=-1
for n,letter in enumerate(s):
if letter in dict1 and dict1[letter] > i:
i=dict1[letter]
dict1[letter] = n
else:
dict1[letter] = n
lenth_max=max(n-i,lenth_max)
print(lenth_max)
return(lenth_max)
效果不错