Leetcode - 139. Word Break
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
class Trie:
def __init__( self ):
self.is_word = False
self.children = {}
def add_words( self, words ):
for word in words:
curr = self
for ch in word:
if ch not in curr.children:
curr.children[ch] = Trie()
curr = curr.children[ch]
curr.is_word = True
class Solution:
def wordBreak( self, s: str, wordDict: List[str] ) -> bool:
trie = Trie()
trie.add_words( wordDict )
n = len( s )
p = [ False ] + [ True ] * ( n )
for i in range( n ):
if p[i] or s[i] not in trie.children:
continue
curr = trie
for j in range( i, n ):
if s[j] not in curr.children:
break
curr = curr.children[ s[j] ]
if curr.is_word:
p[ j + 1 ] = False
return not p[-1]
Leave Leetcode - 139. Word Break to:
Read more #coding posts
Best Posts From Lochard
We have not curated any of lochard's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Lochard
- King's Cross - 45th month of persecution by CCP, LT &UK
- 43rd month, belongings stolen
- Another round of strong damage
- 41st month of humiliation, torture and other crimes
- This is not a prank
- How sick one has to be to take pleasure in drugging and indirectly molesting others?
- Has AI already surpassed humans in morality and emotion?
- Just a reminder that your fellow biped had been treated as non-human for 39 months
- Psychopathy (Chat with AI)
- [Solved] Oracle Linux 10 WiFi adpator not found
- Do you get drugged every day?
- 39th month treated as non-human
- Generated Art (Warning: Disturbing, death symbolism)
- Requesting information about crimes committed by the police
- What are they? What am I?
- Wth is with the world nowadays?
- Everyday being put under effects by devices and substances
- 38th month treated as non-human
- If these define human
- Before: "Are they really police?"; Now: "No wonder."