LeetCode Q 139 - Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:Input: s = "leetcode", wordDict = ["leet", "code"] ; Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.
Example 2:Input: s = "applepenapple", wordDict = ["apple", "pen"]; Output: true
Explanation: Return true because “applepenapple” can be segmented as “apple pen apple”. Note that you are allowed to reuse a dictionary word.
Example 3:Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] ; Output: false
Solution : DP bottom-up
State:
boolean dp[i]
represents ifs.substring(0, i+1)
is valid.state transfer fuction:
For Strings.substring(0, i+1)
, we divide it into two parts, one iss.substring(0, j)
and another iss.substring(j, i+1)
if they are all valid thens.substring(0, i+1)
is valid.
Therefore,dp[i] = dp[j] && wordDict.contains(s.substring(j, i+1));
Caution: when we find one valid partition of s.substring(0, i+1)
, we need to break the for loop.
- boundary cases:
dp[0] = true
.
Code:
public boolean wordBreak(String s, List<String> wordDict) {
if (s == null || s.length() == 0) return true;
if (wordDict == null || wordDict.size() == 0) return false;
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDict.contains(s.substring(j, i+1))) {
dp[i + 1] = true; break;
}
}
}
return dp[s.length()];
}