剑指-面试题48 最长不含重复字符的子字符串

最长不含重复字符的子字符串

题目
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
s . l e n g t h < = 40000 s.length <= 40000 s.length<=40000

思路1 滑动窗口+dp
leetcode题解
        题目中要求答案是子串的长度,故子串一定连续,可以看成一个滑动窗口不断更新窗口的最大值,并维护窗口内不能有重复字符。
(1)初始化头尾指针指向第一个字符
(2)tail右移,同时判断tail指向的字符是否在滑动窗口内

  • 不在,将该元素加入窗口,并更新窗口最大值
  • 在,head右移知道窗口不包含该元素

(3)返回窗口长度历史中的最大值

思路2 哈希表优化滑动窗口

        使用哈希表记录每个字符的下一个索引,然后尽量向右移动尾指针来拓展窗口,并更新窗口的最大长度。如果尾指针指向的元素在哈希表中,将头指针直接移动到重复元素的下一个位置
(1)tail一直向右移动
(2)如果尾指针指向的元素在hash中:

  • head直接跳跃到重复字符的下一位

(3)更新哈希表和窗口长度。


C++ 哈希优化

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> hash;
        int res = 0;
        int head = 0, tail = 0;
        while(tail<s.size())
        {
            if(hash.find(s[tail])!=hash.end())
                head = max(head, hash[s[tail]]+1);			//head跳到重复处的下一位
            hash[s[tail]] = tail;
            res = max(tail-head+1, res);
            ++tail;
        }
        return res;
    }
};

python 哈希优化

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        head = 0
        res = 0
        hashmap = {}
        n = len(s)
        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

python 未优化

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        head = 0
        tail = 0
        if len(s)<2:
            return len(s)
        res = 1
        while tail<len(s)-1:
            tail += 1
            if s[tail] not in s[head:tail]:
                res = max(tail-head+1, res)
            else:
                while s[tail] in s[head:tail]:
                    head += 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值