最小覆盖子串

来源:互联网 发布:淘宝是马云还是日本人 编辑:程序博客网 时间:2024/05/19 17:27

参考

import java.util.HashMap;import java.util.Map;public class Solution {    public String minWindow(String s, String t) {        HashMap<Character, Integer> tp = new HashMap<>();        HashMap<Character, Integer> sp = new HashMap<>();        for (int i = 0, len = t.length(); i < len; i++) {            Character ch = t.charAt(i);            tp.put(ch, (tp.get(ch) == null ? 0 : tp.get(ch)) + 1);        }        int left = 0, right = 0;        sp.put(s.charAt(left), 1);        String ans = null;        while (left <= right) {            if (contains(tp, sp)) {                while (left <= right && contains(tp, sp)) {                    Character ch = s.charAt(left++);                    if (sp.get(ch) == 1) sp.remove(ch);                    else sp.put(ch, sp.get(ch) - 1);                }                if (ans == null || ans.length() > right - (left - 1) + 1) {                    ans = s.substring(left - 1, right + 1);                }            } else {                right++;                if (right >= s.length()) return ans == null ? "" : ans;                Character newKey = s.charAt(right);                sp.put(newKey, (sp.get(newKey) == null ? 0 : sp.get(newKey)) + 1);            }        }        return ans == null ? "" : ans;    }    public boolean contains(HashMap<Character, Integer> a, HashMap<Character, Integer> b) {        for (Map.Entry<Character, Integer> entry : a.entrySet()) {            Character key = entry.getKey();            Integer value = entry.getValue();            if (b.containsKey(key) && b.get(key) != null && b.get(key) >= value) {                continue;            } else {                return false;            }        }        return true;    }}
0 0
原创粉丝点击