792. Number of Matching Subsequences**
https://leetcode.com/problems/number-of-matching-subsequences/description/
题目描述
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
words
andS
will only consists of lowercase letters. - The length of
S
will be in the range of[1, 50000]
. - The length of
words
will be in the range of[1, 5000]
. - The length of
words[i]
will be in the range of[1, 50]
.
C++ 实现 1
这道题需要更快的判断 word
是 S
的子序列.
方法是: 使用 vector<vector<int>> record
用于记录 S
中每个字符的索引, 比如 S = "abac"
, 那么 record
就是 {{0, 2}, {1}, {3}}
, 分别表示 S[i]
的索引. 之后对于 word
中的每个字符 word[i]
, 要求它下一个字符 word[i + 1]
在 S
中的索引, 必须大于 word[i]
在 S
中的索引. 换句话说, 就是 word[i]
和 word[i + 1]
都要出现在 S
中, 并且 word[i + 1]
要出现在 word[i]
之后. 现在的问题是这句话换成代码如何实现? 下面的代码使用 upper_bound
实现了.
class Solution {
private:
vector<vector<int>> record;
bool isSubsequence(const string &word) {
int x = -1;
for (auto &c : word) {
auto it = std::upper_bound(record[c - 'a'].begin(),
record[c - 'a'].end(),
x);
if (it == record[c - 'a'].end()) return false;
x = *it;
}
return true;
}
public:
int numMatchingSubseq(string S, vector<string>& words) {
int count = 0;
record = vector<vector<int>>(26);
for (int i = 0; i < S.size(); ++i) record[S[i] - 'a'].push_back(i);
for (auto &word : words)
if (isSubsequence(word))
count ++;
return count;
}
};