Sword refers to offer 48. The longest substring without repeated characters

Sword refers to offer 48. The longest substring without repeated characters

Title description

Insert picture description here

Problem-solving ideas

Sliding window

class Solution {
    
    
    public int lengthOfLongestSubstring(String s) {
    
    
        if (s == null || s.length() == 0) return 0;
        //窗口的左右边界,左闭右开[left, right),这样窗口大小就是right - left
        int left = 0, right = 0;
        //统计窗口内各字符出现的次数
        Map<Character, Integer> cnt = new HashMap<>();
        int res = 0;

        while (right < s.length()) {
    
    
            char intoWindow = s.charAt(right);
            right++;
            cnt.put(intoWindow, cnt.getOrDefault(intoWindow, 0) + 1);
            while (cnt.get(intoWindow) > 1) {
    
    
                char outOfWindow = s.charAt(left);
                left++;
                cnt.put(outOfWindow, cnt.getOrDefault(outOfWindow, 0) - 1);
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115326751