Question:
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Input: ilikesamsung
Output: Yes
The string can be segmented as "i like samsung" or
"i like sam sung".
I have tried the following recursive approach:
from timeit import timeit
def wordBreak(wordList, word):
word = word.replace(" ", "")
if word == '':
return True
else:
wordLen = len(word)
return any([(word[:i] in wordList)
and wordBreak(wordList, word[i:]) for i in range(1, wordLen+1)])
wordList = ["the", "quick", "fox", "brown"]
word = "the quick brown fox"
print(wordBreak(wordList,word))
print(timeit(lambda: wordBreak(wordList,word))) #12.690028140999999
I also tried using a Trie, which turned out to be way slower after benchmarking the run. Is there an iterative / OOP way of solving the same? Also is my current solution: O(n*(n-1))
in terms of time complexity?