题目描述:
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.
分析
采用双指针遍历,尾指针遍历至包含T的所有字符,首指针尽可能向后压缩,然后在所有窗口中记录最小窗口位置。
PS: 以上两种方法均能通过本地测试,应该没有什么问题,第一种是根据网上别人写的代码改编的。
//给出一个长串(如:S = "ADOBECODEBANC")和一个短串(如:T = "ABC
//找出长串中包含短串的最小字符串(BANC)
//...
//方法一
#include <iostream>
#include <string>
#include <memory.h>
using namespace std; int main(){ string long_str, short_str;
int ShortMark[256], Ben2EndMark[256];
memset(ShortMark, 0, sizeof(ShortMark));
memset(Ben2EndMark, 0, sizeof(Ben2EndMark));
int ansbegin = 0, ansend = 0x3fffffff; freopen("F:\\input.txt", "r", stdin);
cin>>long_str>>short_str;
int count = 0;
for(int i = 0; i < short_str.length(); ++i) ShortMark[short_str[i]] ++; int p_begin = 0, p_end = 0;
while(p_end < long_str.length()){ //如果字符串(begin-end)中存在short_str中的字符,则Ben2EndMark[]对应位置+1;
if(ShortMark[long_str[p_end]]){
Ben2EndMark[long_str[p_end]]++; //如果统计的字符小于等于ShortMark中该字符的个数
if(Ben2EndMark[long_str[p_end]] <= ShortMark[long_str[p_end]])
count ++;
//如果(begin-end)中包含了short_str的所有字符
if(count == short_str.length()){ //cout<< ShortMark[long_str[p_begin]]<<endl;
//cout<< Ben2EndMark[long_str[p_begin]];
while(!ShortMark[long_str[p_begin]] || Ben2EndMark[long_str[p_begin]] > ShortMark[long_str[p_begin]]){
if(Ben2EndMark[long_str[p_begin]] > ShortMark[long_str[p_begin]])
-- Ben2EndMark[long_str[p_begin]];
++ p_begin;
}
//如果窗口更小则...
if(p_end - p_begin < ansend - ansbegin){
ansbegin = p_begin;
ansend = p_end;
} -- Ben2EndMark[long_str[p_begin]];
-- count;
++ p_begin;
}
}
++ p_end;
}
cout<< (ansend - ansbegin + 1);
} //方法二
//#include <iostream>
//#include <string>
//using namespace std;
//
//string long_str, short_str;
//
//bool is_exit(int pstart, int pend, string longstr){
// int count = 0;
// for(int j = 0; j < short_str.length(); ++j){
// for(int i = pstart; i <= pend; ++i){
// if(pstart <= longstr.find(short_str[j]) && longstr.find(short_str[j]) <= pend){
// count ++;
// break;
// }
// }
// }
// if(count == short_str.length())
// return true;
// else
// return false;
//}
//
//int main(){
//
// freopen("F:\\input.txt", "r", stdin);
// cin>>long_str>>short_str;
// int p_start = 0;
// int p_end;
// int LENGTH = 10000;
//
// for(int i = 0; i < long_str.length(); ++i){
// if(is_exit(0, i, long_str)){
// p_end = i;
// break;
// }
// }
// while(p_end <= long_str.length()){
// int TemLong = 10000;
// for(int i = 0; i <= p_end; ++i){
// string Substr = long_str.substr(0, p_end+1);
// string rSunstr(Substr.rbegin(), Substr.rend());//实现逆序排序
// if(is_exit(0, i, rSunstr))
// TemLong = i + 1;
// LENGTH = (LENGTH <= TemLong) ? LENGTH:TemLong;
// }
// ++p_end;
// }
// cout<< LENGTH;
// return 0;
//}