https://leetcode.com/contest/weekly-contest-74/problems/number-of-matching-subsequences/
算是hash思想的扩展把,挺有意思的题。也是想了下才做出。
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<vector<int> > pos;
int ans = 0;
for (int i = 0; i < 26; i++) {
pos.push_back(vector<int>());
}
for (int i = 0; i < S.size(); i++) {
int idx = S[i] - 'a';
pos[idx].push_back(i);
}
for (int i = 0; i < words.size(); i++) {
bool ok = true;
vector<int> wc(26, 0);
int last_match = -1;
for (int j = 0; j < words[i].size(); j++) {
int idx = words[i][j] - 'a';
wc[ idx ] ++;
int match_pos = lower_bound(pos[idx].begin() + wc[idx] - 1, pos[idx].end(), last_match+1) - pos[idx].begin();
if (match_pos == pos[idx].size() ) {
ok = false;
break;
} else {
last_match = pos[idx][match_pos];
}
}
if (ok) {
cout << words[i] << endl;
ans ++;
}
}
return ans;
}
};