Leetcode 792. 匹配子序列的单词数
题目
给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。
示例:
输入:
S = "abcde"
words = ["a", "bb", "acd", "ace"]
输出: 3
解释: 有三个是 S 的子序列的单词: "a", "acd", "ace"。
注意:
- 所有在words和 S 里的单词都只由小写字母组成。
- S 的长度在 [1, 50000]。
- words 的长度在 [1, 5000]。
- words[i]的长度在[1, 50]。
题解
字典树
字典树节点需要中记录下标,我们再构造新节点时,需要保证在之前遍历的节点的下标之后存在当前字母。详细过程见代码
代码
struct Tree{
int index;
bool isWord;
Tree* next[26];
Tree(int index = -1){
for(int i=0; i<26; i++)
next[i] = NULL;
isWord = false;
this->index = index;
}
};
Tree* root;
int numMatchingSubseq(string S, vector<string>& words) {
int n = words.size(),len = S.length();
unordered_map<string,bool> visit; //记录字符串是否可以被匹配,从而避免重复操作
root = new Tree();
int ans = 0;
for(int i=0; i<n; i++){
if(visit.count(words[i]) == 1){
ans += visit[words[i]];
continue;
}
Tree* now = root;
int j;
for(j=0; j<words[i].length(); j++){
if(now->next[words[i][j]-'a'] == NULL){
for(int k=now->index+1; k<len; k++){ //之前遍历的节点下标之后找到第一次出现当前字符的下标,从而进行创建新的节点
if(words[i][j] == S[k]){
Tree* newT = new Tree(k);
now->next[words[i][j]-'a'] = newT;
break;
}
}
}
if(now->next[words[i][j]-'a'] == NULL) break;
now = now->next[words[i][j]-'a'];
}
if(j == words[i].length()){
visit[words[i]] = true;
now->isWord = true;
ans++;
}else visit[words[i]] = false;
}
return ans;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-matching-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。