您的位置:首页 > 其它

[leetcode刷题系列]Minimum Window Substring

2013-08-14 00:38 477 查看
这个也许算是two pointer类型的题目。

先贴一个简单的版本, 这个的复杂度应该算是256 * n

class Solution{
bool ok(int* a, int * b){
for(int c = 0; c < (1 << 8); ++ c)
if(a[c] < b[c])
return false;
return true;
}
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(S.size() <= 0)
return "";
if(T.size() <= 0)
return "";
int hash_s[1 << 8] = {0};
int hash_t[1 << 8] = {0};
for(int i = 0; i < T.size(); ++ i)
hash_t[T[i]] ++;
int st, ans = -1;
int p = -1;
for(int i = 0; i < S.size(); ++ i){
while(p + 1 < S.size() && !ok(hash_s, hash_t))
if(p + 1< S.size()){
++ p;
hash_s[S[p]] ++ ;
}else break;
if(ok(hash_s, hash_t)){
if(ans == -1 || p - i + 1 < ans){
ans = p - i + 1;
st = i;
}
}
hash_s[S[i]] --;
}
if(ans == -1)
return "";
return S.substr(st, ans);
}
};


下面的这个是n+256的复杂度,算是

class Solution{
bool ok(int* a, int * b){
for(int c = 0; c < (1 << 8); ++ c)
if(a[c] < b[c])
return false;
return true;
}
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(S.size() <= 0)
return "";
if(T.size() <= 0)
return "";
int hash_s[1 << 8] = {0};
int hash_t[1 << 8] = {0};
for(int i = 0; i < T.size(); ++ i)
hash_t[T[i]] ++;
for(int i = 0; i < S.size(); ++ i)
hash_s[S[i]] ++ ;
if(!ok(hash_s, hash_t))
return "";
int ans = -1, st = 0;
int p = S.size() - 1;
while(p >= 0){
if(hash_s[S[p]] == hash_t[S[p]])
break;
else{
hash_s[S[p]] --;
-- p;
}
}
// 0
ans = p + 1; st = 0;
for(int i = 1; i < S.size(); ++ i){
char last = S[i - 1];
hash_s[last] --;
if(hash_s[last] >= hash_t[last]){
if(ans > p - i + 1){
ans = p - i + 1;
st = i;
}
}else{
bool find = false;
while(p + 1 < S.size()){
++ p;
hash_s[S[p]] ++ ;
if(S[p] == last){
find = true;
break;
}
}
if(!find)break;
}
}
return S.substr(st, ans);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: