[leetcode] 76. 最小覆蓋子串
阿新 • • 發佈:2018-07-30
lee 一個 || value for com 清醒 substr har
76. 最小覆蓋子串
腦子不清醒的時候,
不要刷題,不要刷題,不要刷題。。。。
我這麽困,為什麽要刷題!
在串S上維護i,j兩個指針,i表示當前包含T所有字母的起始位置,相反j是終止位置。
首先讓j一直加,直到找到了字串s.substring(i,j)滿足條件。之後,j再++,每碰到一個T中擁有的字母,我們就嘗試將i++,直到i不能再加了為止。
class Solution { public String minWindow(String s, String t) { if (t.length() > s.length()) { return ""; } Map<Character, Integer> tmap = new HashMap<>(); Map<Character, Integer> smap = new HashMap<>(); for (int i = 0; i < t.length(); i++) { tmap.putIfAbsent(t.charAt(i), 0); tmap.put(t.charAt(i), tmap.get(t.charAt(i)) + 1); } int i = 0, j = 0, k = -1; int ansi = 0, ansk = Integer.MAX_VALUE; while (j < s.length()) { smap.putIfAbsent(s.charAt(j), 0); smap.put(s.charAt(j), smap.get(s.charAt(j)) + 1); if (tmap.containsKey(s.charAt(j))) { k = j; if (ok(smap, tmap)) { while (!tmap.containsKey(s.charAt(i)) || smap.get(s.charAt(i)) > tmap.get(s.charAt(i))) { // rm i smap.put(s.charAt(i), smap.get(s.charAt(i)) - 1); if (smap.get(s.charAt(i)) == 0) { smap.remove(s.charAt(i)); } i++; } if (k - i < ansk - ansi) { ansi = i; ansk = k; } } } j++; } if (ansk == Integer.MAX_VALUE) { return ""; } return s.substring(ansi, ansk + 1); } private boolean ok(Map<Character, Integer> smap, Map<Character, Integer> tmap) { for (Map.Entry<Character, Integer> entry : tmap.entrySet()) { if (smap.get(entry.getKey()) == null || (entry.getValue() > smap.get(entry.getKey()))) { return false; } } return true; } }
[leetcode] 76. 最小覆蓋子串