#32 Minimum Window Substring

82人阅读 评论(0)

Given a string source and a string target, find the minimum window in source which will contain all the characters in target.

Notice

If there is no such window in source that covers all characters in target, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in source.

Clarification

Should the characters in minimum window has the same order in target?

• Not necessary.
Example

For source = "ADOBECODEBANC", target = "ABC", the minimum window is "BANC"

Challenge

Can you do it in time complexity O(n) ?

Mycode（AC = 28ms）：

class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
*          Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
if (source == "" || target == "") {
return "";
}

// put the chars in target into map
map<char, int> counter;
source = source + " ";
for (int i = 0; i < target.size(); i++) {
if (counter.find(target[i]) != counter.end()) {
counter[target[i]] += 1;
}
else {
counter[target[i]] = 1;
}
}

int l = 0, r = 0;
string ans = "";

// use two pointers to find the minimum length substring
while (r < source.size()) {
if (isValid(counter)) {
string tmp = source.substr(l, r - l);
if (ans == "" || tmp.size() < ans.size()) {
ans = tmp;
}
l++;
}
else {
r++;
}
}

return ans;
}

// add or delete a char in the counter
if (counter.find(key) != counter.end()) {
counter[key] = add? counter[key] + 1: counter[key] - 1;
}
}

// if all chars in target (is valid), then all keys' value in counter should
// be <= 0
bool isValid(map<char, int>& counter) {
for (auto it = counter.begin(); it != counter.end(); it++) {
if (it->second > 0) return false;
}
return true;
}
};


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：11844次
• 积分：2240
• 等级：
• 排名：第16749名
• 原创：221篇
• 转载：1篇
• 译文：0篇
• 评论：10条
文章分类
文章存档
阅读排行
评论排行