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 = "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 are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Java:
http://blog.youkuaiyun.com/linhuanmars/article/details/20343903
这个方法在Substring with Concatenation of All Words和Longest Substring Without Repeating Characters中都介绍过,属于一种类型的题目,只要掌握了思路便可以举一反三,都可以将这类问题降低到线性复杂度。
public class Solution {
public String minWindow(String S, String T) {
if(S==null||S.length()==0) return "";
HashMap<Character, Integer> map=new HashMap<Character, Integer>();
//build dict using T
for(int i=0;i<T.length();i++)
{
if(map.containsKey(T.charAt(i)))
{
map.put(T.charAt(i),map.get(T.charAt(i))+1);
}
else{
map.put(T.charAt(i),1);
}
}
int left=0;
int count=0;
int minLen=S.length()+1;
int minStart=0;
for(int right=0;right<S.length();right++)
{
if(map.containsKey(S.charAt(right)))
{
map.put(S.charAt(right),map.get(S.charAt(right))-1);//find existed char, -1; if repeated char, number will <0
if(map.get(S.charAt(right))>=0)
{
count++; //until all char in dict are found one time;
}
while(count==T.length())
{
if(right-left+1<minLen)
{
minLen=right-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(minLen>S.length())
{
return "";
}
return S.substring(minStart,minStart+minLen);
}
}
本文提供了一种方法,在O(n)复杂度下,找到给定字符串中包含所有目标字符串字符的最短子串。通过构建字典来记录目标字符串的字符及其出现次数,使用双指针技巧优化搜索过程。
770

被折叠的 条评论
为什么被折叠?



