Number of Matching Subsequences

Number of Matching Subsequences

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Example

Input:
S = “abcde”
words = [“a”, “bb”, “acd”, “ace”]
Output: 3
Explanation: There are three words in words that are a subsequence of S: “a”, “acd”, “ace”.

Solution

from collections import defaultdict
class Solution:
    def numMatchingSubseq(self, S: str, words: List[str]) -> int:
        def ifSubseq(word):
            prev_i = -1
            for i,v in enumerate(word):
                if not dict_s[v]:
                    return 0
                for cur_i in dict_s[v]:
                    if prev_i<cur_i and i<=cur_i:
                        prev_i = cur_i
                        break
                    if cur_i == dict_s[v][-1]:
                        return 0
            return 1
        
        count = 0
        dict_s = defaultdict(list)
        for i,v in enumerate(S):
            dict_s[v].append(i)
        for word in words:
            count += ifSubseq(word)
        return count

猜你喜欢

转载自blog.csdn.net/byr_wy/article/details/88710160