题目描述:
给定字符串 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]。
方法1:
主要思路:解题链接汇总
(1)桶排序思路;
(2)将出现过的字符使用当前没有判断过的最前面的字符存储到对应buckets中;
(3)遍历S时,每次使用当前字符从buckets中取出一组索引;
(4)若当前的索引指向的单词已经判断完了全部的字符,则统计结果加1,否则,使用下一个没有判断的字符重新存储到对应的buckets中;
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<vector<pair<int,int>>> buckets(26);
for(int i=0;i<words.size();++i){//first存储的是单词对应的索引,second是当前没有判断的最前面的字符的索引
buckets[words[i][0]-'a'].push_back({i,0});
}
int res=0;
for(char&ch:S){
vector<pair<int,int>> cur=buckets[ch-'a'];//取出当前字符对应的单词索引
buckets[ch-'a'].clear();//情况
for(pair<int,int>& indexs:cur){//判断取出的各个单词
if(words[indexs.first].size()==indexs.second+1){//说明当前单词中的字符已经全部判读完了
++res;
}
else{//重新存储到对应buckets中
++indexs.second;
buckets[words[indexs.first][indexs.second]-'a'].push_back({indexs.first,indexs.second});
}
}
}
return res;
}
};