792. Number of Matching Subsequences
Given string
S
and a dictionary of wordswords
, find the number ofwords[i]
that is a subsequence ofS
.
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".
Note:
- All words in
words
andS
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]
.
Approach #1: Array. [C++]
class Solution { public: int numMatchingSubseq(string S, vector<string>& words) { vector<const char*> waiting[128]; for (auto &w : words) waiting[w[0]].push_back(w.c_str()); for (char c : S) { auto advance = waiting[c]; waiting[c].clear(); for (auto it : advance) waiting[*++it].push_back(it); } return waiting[0].size(); } };
Approach #2: [Java]
class Solution { public int numMatchingSubseq(String S, String[] words) { List<Integer[]>[] waiting = new List[128]; for (int c = 0; c <= 'z'; ++c) waiting[c] = new ArrayList(); for (int i = 0; i < words.length; ++i) waiting[words[i].charAt(0)].add(new Integer[]{i, 1}); for (char c : S.toCharArray()) { List<Integer[]> advance = new ArrayList(waiting[c]); waiting[c].clear(); for (Integer[] a : advance) waiting[a[1] < words[a[0]].length() ? words[a[0]].charAt(a[1]++) : 0].add(a); } return waiting[0].size(); } }
Reference:
https://leetcode.com/problems/number-of-matching-subsequences/discuss/117634/Efficient-and-simple-go-through-words-in-parallel-with-explanation
永远渴望,大智若愚(stay hungry, stay foolish)