792. Number of Matching Subsequences
Medium
49939FavoriteShare
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 inwords
that are a subsequence ofS
: "a", "acd", "ace".
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<vector<int>> Position(26);
int Result = 0;
for(int i = 0;i < S.length();i++){
Position[S[i] - 'a'].push_back(i);
}
for(int i = 0;i < words.size();i ++){
int PrePosition = -1;
bool Flag = true;
for(auto c : words[i]){
auto iter = upper_bound(Position[c - 'a'].begin(),Position[c - 'a'].end(),PrePosition);
if(iter == Position[c - 'a'].end()){
Flag = false;break;
}
else{
PrePosition = *iter;
}
}
if(Flag == true){Result ++;}
}
return Result;
}
};
心得:
利用容器vector将字符串中每一个字符的位置保存下来,之后依次与数组中的字符串进行位置匹配,如果没有那么该字符串不是主字符串的位置。