跳至主要內容

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

专题leetcodeleetcode小于 1 分钟

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

题目:

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

leetcode地址:https://leetcode.cn/problems/longest-substring-without-repeating-characters/open in new window

solution

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> window = new HashMap<>();
        int left = 0;
        int right = 0;
        int res = 0;

        while(right < s.length()) {
            char ch = s.charAt(right);
            right ++;
            window.put(ch, window.getOrDefault(ch, 0) + 1);

            while(window.get(ch) > 1) {
                char aChar = s.charAt(left);
                left++;
                window.put(aChar, window.get(aChar) -1);
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}

版权申明

本站点所有内容,版权均归https://wenchao.renopen in new window所有,除非明确授权,否则禁止一切形式的转载协议

打赏

微信 支付宝

上次编辑于:
打赏
给作者赏一杯咖啡吧
您的支持将是我继续更新下去的动力
微信微信
支付宝支付宝