Suppose we have one non-empty string s and a dictionary wordDict. That is containing a list of non-empty words, determine when s can be segmented into a space-separated sequence of one or more dictionary words. We have to follow some rules −
Suppose the string s = “applepenapple”, and word dictionary is like [“apple”, “pen”], then the output will be true because the string s can be segmented as “apple pen apple”.
Let us see the steps −
Let us see the following implementation to get a better understanding −
class Solution(object): def wordBreak(self, s, wordDict): dp = [[False for i in range(len(s))] for x in range(len(s))] for i in range(1,len(s)+1): for j in range(len(s)-i+1): #print(s[j:j+i]) if s[j:j+i] in wordDict: dp[j][j+i-1] = True else: for k in range(j+1,j+i): if dp[j][k-1] and dp[k][j+i-1]: dp[j][j+i-1]= True return dp[len(s) - 1] ob1 = Solution() print(ob1.wordBreak("applepenapple", ["apple", "pen"]))
"applepenapple" ["apple", "pen"]