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
本题使用动态规划的方法可以轻松解决。
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];//dp[i]代表s.subString(0, i)可以使用wordDict里面的词分割
dp[0] = true;//设置初始条件;s.subString(0, 0)当然满足要求
for(int i = 1; i <= s.length(); ++i) {//依次判断dp[i]的分割序列是否分别存在于wordDict里面
for(int j = 0; j < i; ++j) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {//dp[j]的分割序列和s.substring(j, i)都存在于wordDict里面
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
PS:做了140. Word Break II之后,发现还可以使用DFS的方法来解答。
public boolean wordBreak(String s, List<String> wordDict) {
Map<String, Boolean> map = new HashMap<>();//dp.get(s)表示s的分割集是否都存在于wordDict里
map.put("", true);//初始化
return DFS(s, wordDict, map);
}
private boolean DFS(String s, List<String> wordDict, Map<String, Boolean> map) {
if(map.containsKey(s)) {
return map.get(s);
}
for(int i = 0; i < wordDict.size(); ++i) {
String word = wordDict.get(i);
if(s.startsWith(word) && DFS(s.substring(word.length()), wordDict, map)) {
map.put(s, true);
return true;
}
}
map.put(s, false);
return false;
}