# 139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s 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 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

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.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

# Solution

Approach 1: DP. Time: O(N^3) or O(N*L*L) where L is the avg length of the words -- if using a trie.

# Code (Python)

Approach 1:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        if not s:
            return True
        if not wordDict:
            return False
        dictionary = set(wordDict)
        table = [False for _ in range(len(s) + 1)] # table[i] -- s[0:i] can be broken down
        table[0] = True
        for i in range(1, len(s) + 1):
            for j in range(i - 1, -1, -1): # optimization -- work from the back because word lengths are usually short
                if table[j] and s[j:i] in dictionary: # essentially O(n^3) time because s[j:i] is O(n)
                    table[i] = True
                    break
        return table[-1]
    
        # alternatively can use a trie to put wordDict
        # entire program is now O(N*L*L) where L is the avg length of the words
        #for i in range(1, len(s) + 1): # O(N)
        #    for j in range(i - 1, -1, -1): # O(L)
        #        if table[j] and trie.search(s, j, i-1) # O(L)
        #            table[i] = True
        #            break

# Code (C++)

Approach 1:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int sSize = s.size();
        bool match[sSize + 1] = {false};
        match[sSize] = true;
        for (int i = sSize - 1; i >= 0; --i)
        {
            for (int j = i; j < sSize; ++j)
            {
                string subS = s.substr(i, j - i + 1);
                if (std::find(wordDict.begin(), wordDict.end(), subS) != wordDict.end())
                {
                    match[i] = match[j+1];
                    if (match[i])
                        break;
                }
            }
        }
        return match[0];
    }
};