力扣解法汇总3-无重复字符的最长子串

原题链接:力扣


描述:

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

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

解题思路:

把s转换为char[]类型,然后创建一个map,key为对应的char,value为char对应的index位置。

从左向后遍历,记录start和end。首先去map中查找有没有重复,如果没有,则start不变,end++,maxLength+1,并且把当前字符加入到map当中。

如果有重复,则获取当前字符位置,把map中star到index中所有字符串清空。然后start=index+1,加入到map中继续遍历。

举个例子eabcafdb。

e,a,b,c依次加入到map中,这时候maxLength=4,

读到第4位a时,start=0,index=1,则清掉map中e和a的记录。start改为index+1=2;(从0开始计算)

代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0;
        int end = 0;
        int maxLength = 0;
        char[] chars = s.toCharArray();
        HashMap<Integer, Integer> timeMap = new HashMap<>();

        while (end < chars.length) {
            int aChar = chars[end];
            Integer index = timeMap.get(aChar);
            if (index == null) {
                timeMap.put(aChar, end);
                end++;
                if ((end - start) > maxLength) {
                    maxLength = end - start;
                }
                continue;
            }
            for (int i = start; i < index; i++) {
                timeMap.remove((int) chars[i]);
            }
            start = index + 1;
            timeMap.put(aChar, end);
            end++;
        }

        return maxLength;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值