Skip to main content

【LeetCode 3】无重复字符的最长子串

·71 words·1 min
WFUing
Author
WFUing
A graduate who loves coding.

  • 链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/
import java.util.HashMap;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> win = new HashMap<>();
        int left = 0, right = 0;
        int res = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            win.put(c, win.getOrDefault(c, 0) + 1);
            right++;
            while (win.get(c) > 1) {
                char d = s.charAt(left);
                left++;
                if(win.containsKey(d)) 
                    win.put(d, win.getOrDefault(d, 0) - 1);
            }
           
            res = Math.max(res, right - left);
        }
        return res;
    }
}


💬评论