leetcode_76_最小覆蓋子串

leetcode 76 最小覆蓋子串

  • 題目
    給你一個字符串 S、一個字符串 T,請在字符串 S 裏面找出:包含 T 所有字符的最小子串。
    
    示例:
    
    輸入: S = "ADOBECODEBANC", T = "ABC"
    輸出: "BANC"
    說明:
    
    如果 S 中不存這樣的子串,則返回空字符串 ""。
    如果 S 中存在這樣的子串,我們保證它是唯一的答案。
    
    1. 滑動窗口,check()判斷當前是否滿足覆蓋條件,滿足head後移,不滿足tail後移
      import java.util.Map;
      import java.util.HashMap;
      import java.util.Iterator;
      
      class Solution {
          private Map<Character, Integer> m = new HashMap<Character, Integer>();
          private Map<Character, Integer> tmpcount = new HashMap<Character, Integer>();
      
          private boolean check() {
              Iterator it = m.entrySet().iterator();
              char key;
              int value;
              while (it.hasNext()) {
                  Map.Entry mt = (Map.Entry) it.next();
                  key = (char) mt.getKey();
                  value = (int) mt.getValue();
                  if (tmpcount.getOrDefault(key, 0) < value) return false;
              }
              return true;
          }
      
          public String minWindow(String s, String t) {
              String res = "";
              for (int i = 0; i < t.length(); i++) {
                  char c = t.charAt(i);
                  m.put(c, m.getOrDefault(c, 0) + 1);
              }
              int head = 0;
              int tail = 0;
              while (tail < s.length() || check()) {
                  if (check()) {
                      if (res.length() == 0 || res.length() > (tail - head))
                          res = s.substring(head, tail);
                      char temp = s.charAt(head);
                      tmpcount.put(temp, tmpcount.get(temp) - 1);
                      head++;
                  } else {
                      char temp = s.charAt(tail);
                      tmpcount.put(temp, tmpcount.getOrDefault(temp, 0) + 1);
                      tail++;
                  }
              }
              return res;
          }
      }
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章