Back to DSA
Word Break
mediumGiven a string s and a collection of dictionary words, decide whether s can be decomposed into a sequence of one or more words that all appear in the dictionary. Each dictionary word may be used more than once.
Examples
Example 1:
Input:
s = "applepenapple", wordDict = ["apple","pen"]Output:
trueExplanation: "applepenapple" splits into "apple" + "pen" + "apple".
Example 2:
Input:
s = "pineapplepen", wordDict = ["pine","apple","pen","pineapple"]Output:
trueExplanation: Can be split as "pineapple" + "pen" or "pine" + "apple" + "pen".
Hints
import java.util.*;
class Solution {
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()];
}
}Time complexity
O(n^2)Space complexity
O(n)