Leetcode 808 Solution

This article provides solution to leetcode question 808 (number-of-matching-subsequences)

https://leetcode.com/problems/number-of-matching-subsequences

Solution

class Solution:
    def numMatchingSubseq(self, S: str, words: List[str]) -> int:
        bucket = collections.defaultdict(list)
        for word in words:
            bucket[word[0]].append(word)

        ans = 0
        for ch in S:
            if ch not in bucket:
                continue

            for word in bucket.pop(ch):
                if len(word) == 1:
                    ans += 1
                else:
                    bucket[word[1]].append(word[1:])
        return ans