classSolution: defnumMatchingSubseq(self, s: str, words: List[str]) -> int: ans = 0 for w in words: curr, cnt = 0, 0 for c in w: try: curr = curr + s[curr:].index(c) + 1 cnt += 1 except: break if cnt == len(w): ans +=1 return ans
classSolution: defnumMatchingSubseq(self, s: str, words: List[str]) -> int: ans, bucket = 0, defaultdict(list) for w in words: bucket[w[0]].append(w) for c in s: target, bucket[c] = bucket[c], [] for w in target: iflen(w) == 1: ans += 1 continue bucket[w[1]].append(w[1:]) return ans
Java 版本,好长长长…
classSolution{ privateclassNode{ public String w; publicint p; publicNode(String w, int p){ this.w = w; this.p = p; } } publicintnumMatchingSubseq(String s, String[] words){ List<Node>[] bucket = new ArrayList[26]; int ans = 0; for (int i = 0; i < 26; i++) { bucket[i] = new ArrayList<Node>(); } for (String word : words) { bucket[word.charAt(0) - 97].add(new Node(word, 0)); } for (char c : s.toCharArray()) { List<Node> target = bucket[c - 97]; bucket[c - 97] = new ArrayList<Node>(); for (Node n : target) { if (n.p + 1 == n.w.length()) { ans++; } else { n.p ++; bucket[n.w.charAt(n.p) - 97].add(n); } } } return ans; } }