寻找最长的子字符串

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

双指针+字典+队列,不难,指针遇到就跳转,并把当前的加入,之前的删掉。注意及时保留最大的子字符串的长度。

import collections
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        if not s:  # 双指针
            return 0
        deque1 = collections.deque()
        maxlength = 0
        for i in s:
            if i not in deque1:   # 字典是1,列表是n
                deque1.append(i)
            else:
                if len(deque1) > maxlength:
                    maxlength = len(deque1)
                deque1.append(i)
                val = deque1.popleft()
                while val != i:
                    val = deque1.popleft()
        if len(deque1) > maxlength:
             = len(deque1)
        return maxlength

虽然使用列表判断是否存在某数值的时间复杂度是n,但是可以简洁存储。首先定义一个列表并全部初始化为-1.
在全部都是字母的前提下, i-'a’可以得到距离,把这个距离在列表里对应的位置存储i在字符串中的位置,如果下次遇到了不是-1,说明出现过了。

哈希表+双指针

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        hashmap = {}
        head, res = 0, 0
        for tail in range(n):
            if s[tail] in hashmap:
                head = max(hashmap[s[tail]], head)
            hashmap[s[tail]] = tail + 1
            res = max(res, tail - head + 1)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值