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

本文探讨了如何寻找字符串中最长的无重复字符子串,提供了三种不同的算法实现:队列、滑动窗口和哈希映射。每种方法都详细讲解了其工作原理、时间与空间复杂度。

题目

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

解题思路

Queue

很简单的一道题目,队列即可。用队列记录当前的子串,如果新字符在队列中,则元素依次出队,直到重复的元素出队为止。

改进版可以考虑使用双端队列,popleft()的时间复杂度同样是o(1)o(1)o(1)

时间复杂度:o(s)o(s)o(s)
空间复杂度:o(s)o(s)o(s)

Sliding Window

Use sliding window could reduce the space complexity from o(n)o(n)o(n) to o(1)o(1)o(1), the key is use two pointer to denote the queue above and use a map to keep track of every element we have visited.

Hash Map

Use a hash map to keep track of the character and the index, if it’s duplicate, then move the left to the right of the character that is duplicate with right. Note that both left and right only move forward.

Time complexity: o(n)o(n)o(n)
Space complexity: o(n)o(n)o(n)

代码

Queue

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        queue = []
        max_length = 0
        for ch in s:
            while ch in queue:
                queue.pop(0)
            queue.append(ch)
            max_length = max(max_length, len(queue))
        return max_length

Sliding Window

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        left, right = 0, 0
        res = 0
        visited_char = {}
        for right, ch in enumerate(s):
            while ch in visited_char:
                visited_char.pop(s[left])
                left += 1
            visited_char[ch] = right
            res = max(res, right - left + 1)
        return res

Hash Map

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        char_index = {}
        left = 0
        res = 0
        for right in range(len(s)):
            if s[right] in char_index:
                left = max(left, char_index[s[right]] + 1)
            char_index[s[right]] = right
            res = max(res, right - left + 1)
        return res
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值