LeetCode 0140. Word Break II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0140. Word Break II

Description

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.
  • Input is generated in a way that the length of the answer doesn't exceed 105.

Solutions

Solution 1

PythonJavaGoC#
class Trie: def __init__(self): self.children = [None] * 26 self.is_end = False def insert(self, word): node = self for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.is_end = True def search(self, word): node = self for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: return False node = node.children[idx] return node.is_end class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: def dfs(s): if not s: return [[]] res = [] for i in range(1, len(s) + 1): if trie.search(s[:i]): for v in dfs(s[i:]): res.append([s[:i]] + v) return res trie = Trie() for w in wordDict: trie.insert(w) ans = dfs(s) return [' '.join(v) for v in ans](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !