Prefix DP with a word set
Time O(n × L²) with L the longest word Space O(n + dictionary)ok[0] = true. For each end i, try start j within the maximum word length.
import java.util.*;
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
int maxLen = 0;
for (String w : wordDict) maxLen = Math.max(maxLen, w.length());
boolean[] ok = new boolean[s.length() + 1];
ok[0] = true;
for (int i = 1; i <= s.length(); i++)
for (int j = Math.max(0, i - maxLen); j < i && !ok[i]; j++)
if (ok[j] && words.contains(s.substring(j, i))) ok[i] = true;
return ok[s.length()];
}
}Verdict: Limiting j by word length keeps it fast.