Untitled
unknown
plain_text
a year ago
1.0 kB
7
Indexable
class Solution {
public:
string minWindow(string s, string t) {
vector<int> chars(128, 0); //all ASCII codes
vector<bool> flag(128, false);
int l = 0, min_size = s.size() + 1, min_l = 0, cnt = 0;
// 統計t內的字母
for (int i = 0; i < t.size(); i++){
flag[t[i]] = true;
chars[t[i]]++;
}
for (int r = 0; r < s.size(); r++){
if (flag[s[r]]){ //找到t裡的元素
if (-- chars[s[r]] >= 0) ++cnt;
}
while (cnt == t.size()){
// 找到較短的子字串
if (r - l + 1 < min_size){
min_l = l;
min_size = r - l + 1;
}
// l要向右移 看l所在的元素是否為有用元素
if (flag[s[l]] && ++chars[s[l]] > 0) --cnt; // 不管如何char[s[l]]都會加一
++l;
}
}
return min_size > s.size() ? "" : s.substr(min_l , min_size);
}
};
Editor is loading...
Leave a Comment