Clean Java AC solution


  • 0
    W
        public String minWindow(String s, String t) {
            if (s.length() < t.length()) return "";
            Map<Character, Integer> map = new HashMap<>();
            for (char c : t.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            int start = 0;
            int end = 0;
            int count = 0;
            int min = s.length() + 1;
            String res = "";
            while (end < s.length()) {
                while (end < s.length() && count < t.length()) {
                    char c = s.charAt(end);
                    if (map.containsKey(c)) {
                        if (map.get(c) > 0) {
                            count++;
                        }
                        map.put(c, map.get(c) - 1);
                    }
                    end++;
                }
                while (count >= t.length()) {
                    if (end - start < min) {
                        min = end - start;
                        res = s.substring(start, end);
                    }
                    char c = s.charAt(start);
                    if (map.containsKey(c)) {
                        if (map.get(c) >= 0) {
                            count--;
                        }
                        map.put(c, map.get(c) + 1);
                    }
                    start++;
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.