给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
示例:
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
思路一:
利用递归的思想,注意学习这种递归需要返回值的时候的写法,非常的关键。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return judge(s, wordDict, 0);
}
public static boolean judge(String s, List<String> wordDict, int start) {
if (start == s.length()) {
return true;
}
for (int i = start + 1; i <= s.length(); i++) {
if (wordDict.contains(s.substring(start, i)) && judge(s, wordDict, i)) {
return true;
}
}
return false;
}
}
思路二:
采用动态规划的思路,就是说字符串可以依赖于前面的短一点的字符串的状态。
新建一个dp数组,长度为dp[size + 1],dp[i]表示s[0, i]能否由字典中单词组。并且dp[0] = true,相当于字符串与第一个单词匹配上。
每一次判断dp[i]时,需要参考 前一个单词索引长度的位置的元素。
如果前面的字符串可以组成字典中单词,到了dp[i]的时候仍然是字典中的单词那么dp[i] 就为true
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int size = s.length();
boolean[] dp = new boolean[size + 1];
Set<String> wordSet = new HashSet(wordDict);
// dp[i]表示s[0, i]能否由字典中的单词组成,默认dp[0]为true
dp[0] = true;
for (int i = 1; i <= size; i++) {
for (int j = 0; j < i; j++) {
// 这里的substring(j, i)是因为刚好,dp数组长度比size大1。
if (dp[j] && wordSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[size];
}
}