leetcode Minimum Window Substring答案解析
2015-12-01 21:11
531 查看
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 =
Minimum window is
Note:
If there is no such window in S that covers all characters in T, return the empty string
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
要求查找S中包含T中所有字母的最短子串
解题思路:
建立两个索引表,分别用来存储T中每个字母出现的次数(即needfound)和已经查找过的在start到end中间的各字母的出现次数
class Solution {
public:
string minWindow(string s, string t) {
vector<int> found(128,0);
vector<int> tt(128,0);
for(int i=0;i<t.length();i++)
tt[t[i]]++;
found[s[0]]++;
int count=t.length(),start=0,end=0,ans=s.length()+1,minbegin=0;
if(tt[s[0]]>=found[s[0]])
count--;
while(end<s.length()){
if(count==0){
while(found[s[start]]>tt[s[start]]){
found[s[start]]--;
start++;
}
if(end-start+1<ans){
ans=end-start+1;
minbegin=start;
}
}
end++;
found[s[end]]++;
if(tt[s[end]]>=found[s[end]])
count--;
}
if(ans>s.length())
return "";
return s.substr(minbegin,ans);
}
};
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 empty string
"".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
要求查找S中包含T中所有字母的最短子串
解题思路:
建立两个索引表,分别用来存储T中每个字母出现的次数(即needfound)和已经查找过的在start到end中间的各字母的出现次数
class Solution {
public:
string minWindow(string s, string t) {
vector<int> found(128,0);
vector<int> tt(128,0);
for(int i=0;i<t.length();i++)
tt[t[i]]++;
found[s[0]]++;
int count=t.length(),start=0,end=0,ans=s.length()+1,minbegin=0;
if(tt[s[0]]>=found[s[0]])
count--;
while(end<s.length()){
if(count==0){
while(found[s[start]]>tt[s[start]]){
found[s[start]]--;
start++;
}
if(end-start+1<ans){
ans=end-start+1;
minbegin=start;
}
}
end++;
found[s[end]]++;
if(tt[s[end]]>=found[s[end]])
count--;
}
if(ans>s.length())
return "";
return s.substr(minbegin,ans);
}
};
相关文章推荐
- android Google Map获取地理位置信息的方法
- Spark RDD API详解(一) Map和Reduce
- Python中map()函数浅析
- Android使用Google Map浅谈
- 搜狗百度360市值齐跌:搜索引擎们陷入集体焦虑?
- 本人即将筹备败家日志,敬请期待!
- IE:使用搜索助手
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- Erlang中的映射组Map详细介绍
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解