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

CoderIndeed
0
0139. Word Break

Description

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

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

 

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

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

 

Constraints:

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

Solutions

Solution 1

PythonJavaC++GoTypeScriptRustC#
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: words = set(wordDict) n = len(s) f = [True] + [False] * n for i in range(1, n + 1): f[i] = any(f[j] and s[j:i] in words for j in range(i)) return f[n](code-box)

Solution 2

PythonJavaC++GoTypeScriptC#
class Trie: def __init__(self): self.children: List[Trie | None] = [None] * 26 self.isEnd = False def insert(self, w: str): node = self for c in w: idx = ord(c) - ord('a') if not node.children[idx]: node.children[idx] = Trie() node = node.children[idx] node.isEnd = True class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: trie = Trie() for w in wordDict: trie.insert(w) n = len(s) f = [False] * (n + 1) f[n] = True for i in range(n - 1, -1, -1): node = trie for j in range(i, n): idx = ord(s[j]) - ord('a') if not node.children[idx]: break node = node.children[idx] if node.isEnd and f[j + 1]: f[i] = True break return f[0](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 !