LeetCode 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
分析题意可以发现,最终的答案可以由多个不同的路径走过来,但是题目要求返回的只是最终能不能,因此,我们只需要在每个点返回可以不可以这样一个boolean就行,另外再用一个boolean数组记录是否已经走过此位置,完成优化。但是iteration在理论上是没有进行优化的,就是全部都走完,只有一个剪枝优化就是可以提前返回,但是iteration在空间和语法上是有优化的,因为数组可以bulk load,但是recursion需要不停的从硬盘上来回取数据。
//iteration版本
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>();
for (String ss : wordDict) {
set.add(ss);
}
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
if (set.contains(s.substring(i,j+1)) && dp[i]) {
if (j == s.length() - 1) return true;
dp[j+1] = true;
}
}
}
return false;
}
// recursion版本
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>();
for (String ss : wordDict) {
set.add(ss);
}
boolean[] dp = new boolean[s.length()];
return recursion(s, set, 0, dp);
}
private boolean recursion(String s, HashSet<String> set, int index, boolean[] dp) {
//base case
if (index == s.length()) return true;
if (dp[index] == true) return false;
//recursion
boolean b = false;
for (int i = s.length() - 1; i >= index; i--) {
if (set.contains(s.substring(index, i+1))) {
b = b || recursion(s, set, i+1, dp);
}
}
dp[index] = true;
return b;
}