π One-stop destination for all your technical interview Preparation π
Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
class Solution {
bool isSubsequence(string& s, string& a)
{
int n = s.size(), m = a.size();
if (m > n)
return false;
int i = 0, j = 0;
while (i < n && j < m) {
if (s[i] == a[j]) {
j++;
}
i++;
}
return j == m;
}
public:
int numMatchingSubseq(string s, vector<string>& words)
{
int res = 0;
unordered_map<string, int> wordsMap;
for (auto x : words) {
wordsMap[x]++;
}
for (auto x : wordsMap) {
string newString = x.first;
if (isSubsequence(s, newString)) {
res += x.second;
}
}
return res;
}
};