3. 无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。
暴力搜索的方法并不难,复杂度为O(N^2)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
result=0
for i in range(n):
a_set=()
temp=0
for j in range(i,n):
if s[j] not in a_set:
a_set.add(s[j)
temp+=1
else:
break
result = max(result,temp)
return result
假如有个字符串是a b c d e f g h e m n p,在上面的解法中先从第a开始找一下最大的无重复字符串a->h,再从b开始找最大无重复字符串b->h。其实,从b c d e这些查找都是无用的,因为重复字符串是e,从b c d e开始的最大不重复字符串不会长于从a开始的不重复字符串。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
result = 0
fast,slow = 0,0
a_set = set()
while fast<n:
if s[fast] not in a_set:
a_set.add(s[fast])
result = max(result,fast-slow+1)
fast+=1
else:
a_set.remove(s[slow])
slow += 1
return result
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 逻漫星空
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果