3291. 形成目标字符串需要的最少字符串数 I

Powered by:NEFU AB-IN

Link

文章目录

  • [3291. 形成目标字符串需要的最少字符串数 I](#3291. 形成目标字符串需要的最少字符串数 I)

3291. 形成目标字符串需要的最少字符串数 I

题意

给你一个字符串数组 words 和一个字符串 target。

如果字符串 x 是 words 中 任意 字符串的前缀,则认为 x 是一个 有效 字符串。

现计划通过 连接 有效字符串形成 target ,请你计算并返回需要连接的 最少 字符串数量。如果无法通过这种方式形成 target,则返回 -1。

思路

  1. Trie + 记忆化搜索
    首先就是把所有的word全部放进trie,然后进行记忆化搜索即可
    从target的初始下标开始,去trie中匹配,如果到j匹配上了,然后就dfs(j + 1),如果匹配不上,直接break
    记录每个状态的能被最少几个前缀组成,每次用之后的dfs的值更新这个值即可

代码

python 复制代码
# 3.8.9 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class Std:
    class TrieNode:
        """TrieNode class can quickly process string prefixes, a common feature used in applications like autocomplete and spell checking."""
        _sid_cnt = 0  # sid counter, representing string index starting from 0

        def __init__(self):
            """Initialize children dictionary and cost. The trie tree is a 26-ary tree."""
            self.children_ = {}
            self._sid = -1  # Unique ID for the node, -1 if not assigned

        def add(self, word: str) -> int:
            """Add a word to the trie with the associated cost and return a unique ID."""
            node = self
            for c in word:
                if c not in node.children_:
                    node.children_[c] = Std.TrieNode()
                node = node.children_[c]
            return node._sid

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def minValidStrings(self, words: List[str], target: str) -> int:
        n = len(target)
        trie = Std.TrieNode()

        for word in words:
            trie.add(word)

        @lru_cache(None)
        def dfs(i: int) -> int:
            nonlocal trie
            if i == n:
                return 0
            res = INF

            node = trie
            for j in range(i, n):
                c = target[j]
                if c not in node.children_:
                    break
                sub_res = dfs(j + 1)
                res = Math.min(res, sub_res + 1)
                node = node.children_[c]

            return res

        result = dfs(0)
        dfs.cache_clear()
        return result if result != INF else -1
相关推荐
ComPDFKit8 分钟前
扫描对账单 PDF 转 Excel,怎么查出金额错行?
python·pdf·excel
小白的高手之路32 分钟前
【LeetCode 热题 100】206. 反转链表|链表、迭代、递归(Python)
笔记·python·算法·leetcode·链表·职场和发展·力扣
惯兰高手1 小时前
信阳政务系统开发的消息通知功能实际设计要注意什么?
python
kyh10033811202 小时前
从仿生学到深度学习:人工神经网络原理解析
人工智能·python·深度学习
承渊政道2 小时前
【Python编程快速上手—让繁琐工作自动化】(组织文件:用Python批量改名,把整个文件夹打包备份)
开发语言·python·pycharm·自动化·文件整理·组织文件
Darkwanderor2 小时前
在 Win11 和 CentOS 7.6 安装Python 3.12.7 的流程和踩坑记录
python·腾讯云·python安装·踩坑记录
Metaphor6922 小时前
使用 Python 轻松调整 Word 文档的页边距
python·word·页边距
郝学胜-神的一滴2 小时前
量化交易从入门到精通 04:量化生意的四大特点
开发语言·数据结构·c++·python·算法·pycharm
青少儿编程课堂3 小时前
蓝桥杯青少组图形化真题:校园失物招领智能匹配解析(全国青少年信息素养、电子学会图形化考级同源考点)
c++·python·算法·bfs·信息学竞赛
布语world3 小时前
IDA Pro 9.4 深度解析:DSC 重做、Swift ABI 落地,以及一次被低估的自动化下放
python·安全·ida·app逆向