01
Problem Statement
Given a string s and a list of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. The same word may be reused multiple times. Return false if no such segmentation exists.
- We only need to decide reachability (can we segment the whole string?), not output the actual segmentation.
- Putting
wordDictin aSetgives O(1) lookup for substrings.
02
Key Observations
- Define
dp[i]= can we segment the prefixs[0..i)(length i) using the dictionary? Thendp[i]is true iff there existsjin[0, i-1]such thatdp[j]is true ands.substring(j, i)is in the dictionary. - Base:
dp[0] = true(empty prefix). Forifrom 1 to n, try every splitj: ifdp[j]ands[j..i)in dict, setdp[i] = true. - Use a
SetforwordDictto check substrings in O(1).
03
Approach
High-level: dp[i] = can we segment s[0..i)? For each i, try all j < i: if dp[j] and s.substring(j, i) is in wordDict, set dp[i] = true. Return dp[n].
Steps:
Set<String> set = new HashSet<>(wordDict).dp[0] = true.- For
i = 1..n:dp[i] = false; forj = 0..i-1, ifdp[j]andset.contains(s.substring(j, i)), setdp[i] = true, break. - Return
dp[n].
04
Implementation
Java
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = 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] && set.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}05
Test Cases
Example 1
Input
s = "leetcode", wordDict = ["leet","code"]
Expected
trueExplanation
"leet code".
06
Complexity Analysis
- Time: O(n^2 * word length) with set lookup.
- Space: O(n).
07
Follow-ups
- Word Break II: return all possible segmentations.