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
相关推荐
We་ct2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
做怪小疯子5 小时前
华为笔试0429
python·numpy
Warson_L5 小时前
Dictionary
python
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮7 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说7 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
寒山李白7 小时前
解决 python-docx 生成的 Word 文档打开时弹出“无法读取内容“警告
python·word·wps·文档·docx·qoder
wuweijianlove8 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung8 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了8 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划