题目来源:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解法一:双指针(滑动窗口)
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
if n < 2:
return n
low = 0
res = 0
for high in range(n):
if s[high] not in s[low:high]:
res = max(res, high - low + 1)
else:
while s[high] in s[low:high]: # 处理连续重复的情况
low += 1
return res
时间复杂度: ,列表的in操作需要O(n),外层循环O(n)
空间复杂度:,只有两个指针的额外存储
解法二:滑动窗口+哈希表(优化时间)
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
if n < 2:
return n
low = 0
res = 0
dct = {} # 哈希表存储元素的索引,如果元素已存在则更新索引值
for high in range(n):
if s[high] in dct:
low = max(low, dct[s[high]] + 1)
dct[s[high]] = high
res = max(res, high - low + 1)
return res
时间复杂度:,一个外层循环,哈希表的查找为常数时间
空间复杂度:,哈希表
参考: