Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S =
T =
S =
"ADOBECODEBANC"
T =
"ABC"
Minimum window is
"BANC"
.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string
If there is no such window in S that covers all characters in T, return the emtpy string
""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
这道题是字符串处理的题目,和Substring with Concatenation of All Words思路非常类似,同样是建立一个字典,然后维护一个窗口。区别是在这道题目中,因为可以跳过没在字典里面的字符(也就是这个串不需要包含且仅仅包含字典里面的字符,有一些不在字典的仍然可以满足要求),所以遇到没在字典里面的字符可以继续移动窗口右端,而移动窗口左端的条件是当找到满足条件的串之后,一直移动窗口左端直到有字典里的字符不再在窗口里。在实现中就是维护一个HashMap,一开始key包含字典中所有字符,value就是该字符的数量,然后遇到字典中字符时就将对应字符的数量减一。算法的时间复杂度是O(n),其中n是字符串的长度,因为每个字符再维护窗口的过程中不会被访问多于两次。空间复杂度则是O(字典的大小),也就是代码中T的长度。
public class Solution { public String minWindow(String s, String t) { int m = s.length(); int n = t.length(); if (m == 0 || n == 0 || s == null || t == null) { return ""; } HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < n; i++) { if (!map.containsKey(t.charAt(i))) { map.put(t.charAt(i), 1); } else { map.put(t.charAt(i), map.get(t.charAt(i)) + 1); } } int minL = m+1; int count = 0; int minstart = 0; int left = 0; for (int i = 0; i < m; i++) { if (map.containsKey(s.charAt(i))) { map.put(s.charAt(i), map.get(s.charAt(i)) - 1); if (map.get(s.charAt(i)) >= 0) { count++; } while (count == n) { if (i - left + 1 < minL) { minL = i - left + 1; minstart = left; } if (map.containsKey(s.charAt(left))) { map.put(s.charAt(left), map.get(s.charAt(left)) + 1); if (map.get(s.charAt(left)) > 0) { count--; } } left++; } } } if (minL > m) { return ""; } return s.substring(minstart, minstart + minL); } }
没有评论:
发表评论