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

题目地址

标签:滑动窗口,降低时间复杂度

  1. 定义一个 map 数据结构存储 (k, v),其中 key 值为字符,value 值为字符位置(位置是从0开始的)。
  2. 我们定义不重复子串的开始位置为 start,结束位置为 end。随着 end 不断遍历向后,会遇到与 [start, end] 区间内字符相同的情况,此时将字符作为 key 值,获取其 value 值,并更新 start(注意代码里取max值的理解),此时 [start, end] 区间内不存在重复字符
  3. 无论是否更新 start,都会更新其 map 数据结构和结果 ans。

解题思路

class Solution {
    /**
     * map (k, v),其中 key 值为字符,value 值为字符位置;
     */
    public int lengthOfLongestSubstring(String s) {
        int length = s.length();
        int max = 0;

        Map<Character, Integer> map = new HashMap<>();
        for(int start = 0, end = 0; end < length; end++){
            char element = s.charAt(end);
            if(map.containsKey(element)){
                start = Math.max(map.get(element) + 1, start); //map.get()的地方进行+1操作;这里取最大值而不是map.get(element) + 1的原因是排除abba这种情况:当验证到第二个a时,start应该第二个b,如果只用map.get(element) + 1的话,start就是第一个b,就出错了。         
            }
            max = Math.max(max, end - start + 1);
            map.put(element, end);
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值