Leetcode 3291. Minimum Number of Valid Strings to Form Target I

1. 解题思路

这一题第一反应就是用一个字典树+动态规划的方式,倒是也搞定了,不过对于下一题就搞不定了,感觉还是得进一步优化一下,不过对这道题倒是也算ok了。

2. 代码实现

给出python代码实现如下:

class Trie:
    def __init__(self):
        self.trie = {}
    
    def add_word(self, word):
        trie = self.trie
        for c in word:
            trie = trie.setdefault(c, {})
        trie["eos"] = ""

    def find(self, word):
        trie = self.trie
        for c in word:
            if c not in trie:
                return False
            trie = trie[c]
        return "eos" in trie

class Solution:
    def minValidStrings(self, words: List[str], target: str) -> int:
        trie = Trie()
        for w in words:
            trie.add_word(w)
            
        n = len(target)
        
        @lru_cache(None)
        def dp(idx):
            if idx >= n:
                return 0
            _trie = trie.trie
            ans = math.inf
            while idx < n and target[idx] in _trie:
                _trie = _trie[target[idx]]
                idx += 1
                ans = min(ans, 1+dp(idx))
            return ans
        
        ans = dp(0)
        return ans if ans != math.inf else -1

提交代码评测得到:耗时12771ms,占用内存41.8MB。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值