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.
- For example,
"ace"
is a subsequence of"abcde"
.
Example 1:
Input: s = "abcde", words = ["a","bb","acd","ace"] Output: 3 Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Example 2:
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"] Output: 2
Constraints:
1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
s
andwords[i]
consist of only lowercase English letters.
class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
buckets = defaultdict(list)
for word in words:
buckets[word[0]].append(word)
res = 0
for c in s:
old = buckets[c][::1]
buckets[c].clear()
for t in old:
if len(t) == 1:
res += 1
else:
buckets[t[1]].append(t[1:])
return res
class Solution {
public int numMatchingSubseq(String s, String[] words) {
List<String>[] buckets = new List[26];
for (int i = 0; i < buckets.length; ++i) {
buckets[i] = new ArrayList<>();
}
for (String word : words) {
buckets[word.charAt(0) - 'a'].add(word);
}
int res = 0;
for (char c : s.toCharArray()) {
List<String> old = new ArrayList<>(buckets[c - 'a']);
buckets[c - 'a'].clear();
for (String t : old) {
if (t.length() == 1) {
++res;
} else {
buckets[t.charAt(1) - 'a'].add(t.substring(1));
}
}
}
return res;
}
}
class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words) {
vector<vector<string>> buckets(26);
for (auto word : words) buckets[word[0] - 'a'].push_back(word);
int res = 0;
for (auto c : s)
{
auto old = buckets[c - 'a'];
buckets[c - 'a'].clear();
for (auto t : old)
{
if (t.size() == 1) ++res;
else buckets[t[1] - 'a'].push_back(t.substr(1));
}
}
return res;
}
};
func numMatchingSubseq(s string, words []string) int {
buckets := make([][]string, 26)
for _, word := range words {
buckets[word[0]-'a'] = append(buckets[word[0]-'a'], word)
}
res := 0
for _, c := range s {
old := buckets[c-'a']
buckets[c-'a'] = nil
for _, t := range old {
if len(t) == 1 {
res++
} else {
buckets[t[1]-'a'] = append(buckets[t[1]-'a'], t[1:])
}
}
}
return res
}