版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/90140648
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 and S 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].
分析
题目的意思是:给定字典words,和一个字符串S,问字典中有多少个字符串是S的字串。
- 用一个26位的数组alpha存储S种每个字符的索引。然后对于words,用二分法查找每个word中每个字符c的索引是否存在,如果二分查找找到了尾部,说明索引不存在,则这个单词就不是S的substring。
- upper_bound(a.begin(),a.end(),x)返回的是迭代器
代码
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<vector<int>> alpha(26);
for(int i=0;i<S.size();i++){
alpha[S[i]-'a'].push_back(i);
}
int res=0;
for(auto word:words){
int x=-1;
bool found=true;
for(char c:word){
auto it=upper_bound(alpha[c-'a'].begin(),alpha[c-'a'].end(),x);
if(it==alpha[c-'a'].end()){
found=false;
break;
}else{
x=*it;
}
}
if(found){
res++;
}
}
return res;
}
};
参考文献
792. Number of Matching Subsequences
C++STL中的upper_bound()函数的使用