# Word Break in Python

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 −

• The same word in the dictionary may be reused multiple numbers of times in the segmentation.
• We can assume that the dictionary does not contain duplicate words.

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 −

• Define one matrix DP of order n x n. n = size of the string, and initialize it with false
• for i in range 1 to length of s
• for j in range 0 to length of s – i
• if substring s[j to j + 1] in dictionary, then dp[j, j+i - 1] := True
• otherwise
• for k in range j + 1 to j + i
• if dp[j, k - 1] and dp[k, j + i – 1], then dp[j, j + i – 1] := True
• return DP[0, length of s - 1]

## Example(Python)

Let us see the following implementation to get a better understanding −

Live Demo

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[0][len(s) - 1]
ob1 = Solution()
print(ob1.wordBreak("applepenapple", ["apple", "pen"]))

## Input

"applepenapple"
["apple", "pen"]

## Output

true