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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值