792. Number of Matching Subsequences
Problem Description
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
Analysis and Solution
基本思路是对words
中的每一个word
检查是否为S的一个子序列。但是如果每次检查都要扫描一遍S的话时间复杂度太高,所以就想到把S中字母的位置存储起来提高效率。扫描一遍字符串S并建立一个字典,记录每一个字母出现的位置并按照升序排列。对每一个word
,遍历word
并查找字典中当前字母的出现位置并保持其相对位置不变。代码如下:
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
// build the dictionary
vector<vector<int>> pos(26);
for (int i=0; i<S.size(); i++) {
pos[S[i] - 'a'].push_back(i);
}
int count = 0;
for (int i=0; i<words.size(); i++) {
int j = 0, cur = -1;
// iterate each letter in the word
while (j != words[i].size()) {
int k = 0;
while (k != pos[words[i][j] - 'a'].size()) {
// keep the relative positions by greedy
if (pos[words[i][j] - 'a'][k] > cur) {
cur = pos[words[i][j] - 'a'][k];
break;
}
k++;
}
// when there is no match, break to prune
if (k == pos[words[i][j] - 'a'].size()) {
break;
}
j++;
}
// the case every letter could be matched
if (j == words[i].size()) count++;
}
return count;
}
};