792. Number of Matching Subsequences
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
Example :
Input:
S = "abcde"
words = ["a", "bb", "acd", "ace"]
Output: 3
Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace".Note:
All words in
wordsandSwill only consists of lowercase letters.The length of
Swill be in the range of[1, 50000].The length of
wordswill be in the range of[1, 5000].The length of
words[i]will be in the range of[1, 50].
int numMatchingSubseq(string S, vector<string>& words) { // time: O(words_len * average str_len * log(S_len)); space: O(S_len)
// Build a lookup index table
vector<vector<int> > idx(26);
for (int i = 0; i < S.length(); ++i) idx[S[i] - 'a'].push_back(i);
int res = 0;
for (string& word : words) {
int prev = -1;
bool found = true;
for (char c : word) {
auto it = upper_bound(idx[c - 'a'].begin(), idx[c - 'a'].end(), prev);
if (it == idx[c - 'a'].end()) {
found = false;
break;
} else prev = *it;
}
if (found) ++res;
}
return res;
}Last updated
Was this helpful?