intnumMatchingSubseq(string S, vector<string>& words){ vector<vector<int>> store(26, vector<int>()); for (int i = 0; i < S.size(); ++i) { // 存储字母跟index store[S[i] - 'a'].push_back(i); }
int res = 0; for (auto &word: words) { int x = -1; bool found = true; for (auto c: word) { // search auto it = upper_bound(store[c - 'a'].begin(), store[c - 'a'].end(), x); if (it == store[c - 'a'].end()) { found = false; break; } else { // 更新最新的下标位置 x = *it; } } if (found) res++; }
return res; }
Solution 2
第二种思路,来自Stefan大神。 这种思路,存储的是words中等待匹配的字符的index pair。比如 words = [“a”, “bb”, “acd”, “ace”]存储的结果是:
idx
pair
‘a’
[(0, 1), (2, 1), (3, 1)]
‘b’
[(1, 1)]
1 2 3 4 5 6 7 8 9 10 11 12 13
intnumMatchingSubseq(string S, vector<string>& words){ vector<pair<int, int>> waiting[128]; for (int i = 0; i < words.size(); i++) waiting[words[i][0]].emplace_back(i, 1); for (char c : S) { auto advance = waiting[c]; waiting[c].clear(); for (auto it : advance) waiting[words[it.first][it.second++]].push_back(it); }