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

xkrivzooh2023年3月8日
小于 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;
    }
}
上次编辑于: 2023/3/8 13:39:50
Loading...