Algo-Sim › Dynamic Programming

Word Break

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

dp[i] is true when some reachable cut j leaves s[j..i) as a dictionary word. The arcs show successful and short candidates; counters include all checked substrings.

Problem

Given a string s and a list of words wordDict, return true if s can be split into a sequence of one or more dictionary words, with no letters left over. A word may be used more than once.

Constraints

Edge cases to test

Follow-up questions

How do you speed up the inner loop?
Only try cuts up to the longest word length, or walk a trie of the words from each reachable start.
How do you list every sentence?
Backtrack with memoised suffix results (LC 140); the output can be exponential.

Solution

Java

public boolean wordBreak(String s, List<String> wordDict) {
    Set<String> words = new HashSet<>(wordDict);
    boolean[] dp = new boolean[s.length() + 1];
    dp[0] = true;
    for (int i = 1; i <= s.length(); i++) {
        for (int j = 0; j < i; j++) {
            if (dp[j] && words.contains(s.substring(j, i))) {
                dp[i] = true;
                break;
            }
        }
    }
    return dp[s.length()];
}

Python

def word_break(s, word_dict):
    words = set(word_dict)
    dp = [False] * (len(s) + 1)
    dp[0] = True
    for i in range(1, len(s) + 1):
        for j in range(i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break
    return dp[len(s)]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool wordBreak(string &s, vector<string> &wordDict) {
        unordered_set<string> words = unordered_set<string>(wordDict.begin(), wordDict.end());
        vector<bool> dp = vector<bool>(int(s.size()) + 1);
        dp[0] = true;
        for (int i = 1; i <= int(s.size()); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && words.count(s.substr(j, (i) - (j)))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[int(s.size())];
    }
};

More Dynamic Programming problems