Algorithm Puzzles: Word Break
Algorithm Puzzles everyday every week sometimes: Algorithm Puzzles: Word Break
Puzzle
Puzzle from leetcode:
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.
Solution
First Came Out Solution
It can be easily implemented via recursion, but will hit Time Limit Exceeded error:
1 | class Solution: |
DP
Let dp[i] == true if (dp[i-len(word)] == true && s[i-len(word):i] == word)
1 | class Solution: |