您的位置:首页 > 其它

LeetCode —— Minimum Window Substring

2013-04-19 21:15 330 查看
链接:http://leetcode.com/onlinejudge#question_76

原题:

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.
思路:这题想了好长时间,STL的unordered_map也用的不熟,调试也很痛苦。

主要思想是用hash表存储T子串,用首尾索引来跟踪窗口。

第一步:找到一个包含T字符的窗口

第二步:把头部不必要的字符去掉,得到一个窗口长度值

第三步:继续把尾部索引向前走,如果出现和首部索引一样的字母,那么去掉头部的一些不必要字母,

形成新的窗口,比较长度值。

代码写丑了,写完后,查了一下,感觉自己的代码组织能力实在是太差了,这位大神给了个很漂亮的代码

/article/8910420.html

class Solution {
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (S.size() < T.size() || T.size() == 0)
return "";

unordered_multiset<char> hashSet;
unordered_map<char, int> counter;
unordered_map<char, int> benchmark;
for (int i=0; i<T.size(); i++) {
if (benchmark.find(T[i]) != benchmark.end())
benchmark[T[i]] += 1;
else
benchmark[T[i]] = 1;
}
for (int i=0; i<T.size(); i++)
hashSet.insert(T[i]);
int start;
int n = 0;
vector<bool> flags(S.size(), false);
for ( ; n < S.size(); n++) {
unordered_multiset<char>::iterator itr = hashSet.find(S
);
if (itr != hashSet.end()) {
hashSet.erase(itr);
start = n;
flags
= true;
counter[S
] = 1;
break;
}
}
if (hashSet.empty())
return S.substr(start, 1);
for (n++; n < S.size(); n++) {
unordered_multiset<char>::iterator itr = hashSet.find(S
);
if (itr != hashSet.end())
hashSet.erase(itr);
if (benchmark.count(S
) > 0) {
flags
= true;
if (counter.count(S
) > 0)
counter[S
] += 1;
else
counter[S
] = 1;
}

if (hashSet.empty())
break;
}

if (!hashSet.empty())
return "";
int pos = start;
while (true) {
if (flags[pos]) {
if (benchmark[S[pos]] < counter[S[pos]])
counter[S[pos]]--;
else
break;
}
pos++;
}
start = pos;
int minLen = n - start + 1;

for (n++; n < S.size(); n++) {
if (counter.find(S
) != counter.end()) {
counter[S
] += 1;
flags
= true;
}
if (S
== S[start] ){
while (true) {
if (flags[start]) {
if (benchmark[S[start]] < counter[S[start]])
counter[S[start]]--;
else
break;
}
start++;
}
if (n - start + 1 < minLen) {
minLen = n - start + 1;
pos = start;
}
}
}

return S.substr(pos, minLen);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: