[leetcode]792. Number of Matching Subsequences
Analysis
明天就是除夕啦—— [每天刷题并不难0.0]
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
Explanation:
递归~
Implement
最开始试图用map标记每个单词中字符出现的次数,然后与S比较,但是发现这样的话会忽略字符出现的顺序,心塞
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
unordered_map<char, int> mmp;
for(auto c:S){
if(mmp.find(c) != mmp.end())
mmp[c]++;
else
mmp[c] = 1;
}
int len = words.size();
int cnt = 0;
for(int i=0; i<len; i++){
unordered_map<char, int> mmp1;
for(auto c:words[i]){
if(mmp1.find(c) != mmp1.end())
mmp1[c]++;
else
mmp1[c] = 1;
}
bool flag = true;
for(auto it:mmp1){
if(mmp[it.first] < it.second){
flag = false;
break;
}
}
if(flag)
cnt++;
}
return cnt;
}
};
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<pair<int, int>> wait[128];
int len = words.size();
for(int i=0; i<len; i++)
wait[words[i][0]].emplace_back(i, 1);
for(char c:S){
auto tmp = wait[c];
wait[c].clear();
for(auto it:tmp)
wait[words[it.first][it.second++]].push_back(it);
}
return wait[0].size();
}
};