139. Word Break
Asked at 26Amazon59Apple59Bloomberg58Meta54Microsoft51Google44Walmart Labs82Grammarly67Pocket Gems100Coupang97Yahoo97MongoDB91Millennium76Compass74Intuit70Zeta64Uber62Arista Networks60Nutanix60Autodesk59Netflix58TikTok56Palo Alto Networks50Visa39Oracle27LinkedIn20
Problem
Decide whether s can be split into a sequence of one or more words from wordDict (words may be reused).
Example: s = "applepenapple", wordDict = ["apple","pen"] → true; s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] → false
Constraints: length ≤ 300.
dp[i] = s[:i] can be segmented = exists j < i with dp[j] and s[j:i] in the dictionary. Limit j to the max word length.
Complexity: O(n · L) substring checks.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
L = max(map(len, words))
dp = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
for j in range(max(0, i - L), i):
if dp[j] and s[j:i] in words:
dp[i] = True
break
return dp[-1]
assert Solution().wordBreak("leetcode", ["leet", "code"]) is True
assert Solution().wordBreak("applepenapple", ["apple", "pen"]) is True
assert Solution().wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]) is False
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
int L = 0;
for (String w : words) L = Math.max(L, w.length());
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++)
for (int j = Math.max(0, i - L); j < i && !dp[i]; j++)
dp[i] = dp[j] && words.contains(s.substring(j, i));
return dp[s.length()];
}
}
func wordBreak(s string, wordDict []string) bool {
words, L := map[string]bool{}, 0
for _, w := range wordDict {
words[w] = true
L = max(L, len(w))
}
dp := make([]bool, len(s)+1) // dp[i]: s[:i] can be segmented
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := max(0, i-L); j < i; j++ { // the last word is at most L long
if dp[j] && words[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}