Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-window-substring.cpp 1.39 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-05-20 13:16 +08:00 . Update minimum-window-substring.cpp
// Time: O(n)
// Space: O(k)
class Solution {
public:
string minWindow(string s, string t) {
if (s.empty() || s.length() < t.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> exp_cnt(ASCII_MAX, 0);
vector<int> cur_cnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_start = 0;
int min_width = numeric_limits<int>::max();
for (const auto& c : t) {
++exp_cnt[c];
}
for (int i = 0; i < s.length(); ++i) {
if (exp_cnt[s[i]] > 0) {
++cur_cnt[s[i]];
if (cur_cnt[s[i]] <= exp_cnt[s[i]]) { // Counting expected elements.
++cnt;
}
}
if (cnt == t.size()) { // If window meets the requirement.
while (exp_cnt[s[start]] == 0 || // Adjust left bound of window.
cur_cnt[s[start]] > exp_cnt[s[start]]) {
--cur_cnt[s[start]];
++start;
}
if (min_width > i - start + 1) { // Update minimum window.
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == numeric_limits<int>::max()) {
return "";
}
return s.substr(min_start, min_width);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助