74th LeetCode Weekly Contest Valid Number of Matching Subsequences

时间:2023-03-08 23:47:09
74th LeetCode Weekly Contest Valid Number of Matching Subsequences

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].

问S中有多少符合words里面的单词(可以不连续哦)

当然是二分啊,我们保存S中字母的位置,对于每个words我们都查找字母的位置,然后+1一位继续找

 class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
int num=;
vector<int>vec[];
int len=S.size();
for(int i=;i<len;i++){
vec[S[i]-'a'].push_back(i);
}
for(auto word:words){
int add=;
int wordLen=word.size();
int flag=;
// cout<<word<<endl;
for(int i=;i<wordLen;i++){
if(vec[word[i]-'a'].size()==){
flag=;
break;
}
auto it=lower_bound(vec[word[i]-'a'].begin(),vec[word[i]-'a'].end(),add);
if(it==vec[word[i]-'a'].end()){
flag=;
break;
}
add=(*it);
add++;
// cout<<add<<endl;
}
if(flag){
num++;
}
}
return num;
}
};