This is Leetcode problem 139: "Wordbreak"
Problem: Given a non-empty string
s
and a dictionarywordDict
containing a list of non-empty words, determine ifs
can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.
Example:
- 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. my solution
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
"""
"""
def prune(i):
if i == len(s):
return True
elif i >len(s):
return False
else:
for word in wordDict:
m = len(word)
if s[i:i+m] == word and prune(i+m):
return True
return False
wordDict.sort(key = lambda x:-len(x))
return prune(0)
I believe the time complexity for my solution to be O(m^n), where m is the amount of words in wordDict
and n is the length of the string s
. Space wise is just the recursion stack so O(n). I'm having a hard time figuring out how to optimize my solution by either using bfs/dfs or dynamic programming. What would I memoize?