跳转至

140.word-break-ii

Statement

Metadata
  • Link: 单词拆分 II
  • Difficulty: Hard
  • Tag: 字典树 记忆化搜索 哈希表 字符串 动态规划 回溯

给定一个字符串 s 和一个字符串字典 wordDict ,在字符串 s 中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。

注意:词典中的同一个单词可能在分段中被重复使用多次。

 

示例 1:

输入:s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
输出:["cats and dog","cat sand dog"]

示例 2:

输入:s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
输出:["pine apple pen apple","pineapple pen apple","pine applepen apple"]
解释: 注意你可以重复使用字典中的单词。

示例 3:

输入:s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
输出:[]

 

提示:

  • 1 <= s.length <= 20
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 10
  • s 和 wordDict[i] 仅有小写英文字母组成
  • wordDict 中所有字符串都 不同

Metadata
  • Link: Word Break II
  • Difficulty: Hard
  • Tag: Trie Memoization Hash Table String Dynamic Programming Backtracking

Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

 

Example 1:

Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]

Example 2:

Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []

 

Constraints:

  • 1 <= s.length <= 20
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 10
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

Solution

from typing import List


class Solution:
    def __init__(self) -> None:
        self.wd = {}
        self.n = 0
        self.res = []
        self.s = ""

    def dfs(self, idx: int, cur_str: str, cur_str_list: List[str]) -> None:
        if idx == self.n:
            if len(cur_str) == 0:
                self.res.append(" ".join(cur_str_list))
            return

        cur_str += self.s[idx]
        self.dfs(idx + 1, cur_str, cur_str_list)

        if cur_str in self.wd.keys():
            cur_str_list.append(cur_str)
            self.dfs(idx + 1, "", cur_str_list)
            cur_str_list.pop()

    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        self.s = s
        self.n = len(s)

        for w in wordDict:
            self.wd[w] = 1

        self.dfs(0, "", [])

        return self.res

最后更新: January 15, 2023
回到页面顶部