leetcode 3. 无重复字符的最长子串

无重复字符的最长子串

Version 1

思路

  • 使用队列deque来实现滑动窗口

Code

python 复制代码
from collections import deque

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)
            
        queue = deque()
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in queue:
                queue.append(cur_str)
            else:
                
                while cur_str in queue:     ### 收缩窗口
                    queue.popleft()
                    left += 1

                queue.append(cur_str)

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length

Version 2

思路

  • 使用Set进行O(1)级别的查询以优化收缩窗口的判断实现

Code

python 复制代码
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)

### V2

        hash_set = set()
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in hash_set:
                hash_set.add(cur_str)
            else:
                
                while cur_str in hash_set:     ### 收缩窗口
                    pre_str = s[left]
                    hash_set.remove(pre_str)
                    left += 1                  ### 去掉重复的字母后向右移一位

                hash_set.add(cur_str)

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length

Version 3

思路

  • 字符串本身也快速实现判断一个 子字符串 在 原字符串 中

Code

python 复制代码
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)


        max_str = ""
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in max_str:
                max_str += cur_str
            else:
                while cur_str in max_str:     ### 收缩窗口
                    max_str = max_str[1:]                ### 从左到右逐渐去掉字符
                    left += 1                  ### 去掉重复的字母后向右移一位

                max_str += cur_str

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length
相关推荐
2401_8275602017 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
ohyeah17 小时前
栈:那个“先进后出”的小可爱,其实超好用!
前端·数据结构
BBB努力学习程序设计17 小时前
Python自动化脚本:告别重复劳动
python·pycharm
BBB努力学习程序设计17 小时前
Python函数式编程:优雅的代码艺术
python·pycharm
2501_9409439118 小时前
体系课\ Python Web全栈工程师
开发语言·前端·python
散峰而望18 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
q***952218 小时前
SpringMVC 请求参数接收
前端·javascript·算法
田姐姐tmner18 小时前
Python切片
开发语言·python
初级炼丹师(爱说实话版)18 小时前
多进程与多线程的优缺点及适用场景总结
算法
t***316518 小时前
爬虫学习案例3
爬虫·python·学习