题目:
给定一个非空字符串 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
思路:网上找的大神的代码,原文链接:https://blog.csdn.net/mine_song/article/details/72081998。
以下的代码采用的是动态优化的思想。首先设置一个字符数组dp,其中dp[i]表示前i个字符串能不能被dict完美划分,如果可以的话,就将其值设置为true;设置dp[0]为true,dp[i]能否被完美划分与两部分有关,一个是dp[j](0<=j<i)是否为true,和字符( s.substring(j, i),注意这里是前并后开,包含第j个字符,不包含第i个字符,从0开始)是否包含在字典中,这两个条件需要同时满足。这块判断是否包含在字典中时,不需要在编程序,字典使用list实现,直接使用list中的contains()方法判断。
代码1:
class Solution {
public boolean wordBreak(String s, List<String> dict) {
int len = s.length();
//len+1
//dp[i]表示前i个字符能不能被dict完美划分
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for (int i = 1; i <= len; i++)
for (int j = 0; j < i; j++) {
// 注意substring是前闭后开
String tmp = s.substring(j, i);
//能否组合出f[i]表示的子串,k表示组合中前半段的
if (dp[j] && dict.contains(tmp)) {
dp[i] = true;
break;
}
}
return dp[len];
}
}
代码2:
这个问题可以看成是一个完全背包问题的变形,将代码写在下面。但是这个代码的运行时间比最快代码要慢。
这个体重是一个涉及到顺序的背包问题,需要把对背包重量的迭代写在外循环,将对物品的迭代写在内循环
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (String word : wordDict) { // 对物品的迭代应该放在最里层
int len = word.length();
if (len <= i && word.equals(s.substring(i - len, i))) {
dp[i] = dp[i] || dp[i - len];
}
}
}
return dp[n];
}
执行最快的代码:
和代码1的思路基本上是一致的。但是在一些地方做了优化。首先对于j是从后往前进行判断,其次是j的范围,不再是j<i,而是(i-j<=字典中最大的字符长度)&&(j>=0)。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// 可以类比于背包问题
int n = s.length();
int max_length=0;
for(String temp:wordDict){
max_length = temp.length()>max_length? temp.length():max_length;
}
// memo[i] 表示 s 中以 i - 1 结尾的字符串是否可被 wordDict 拆分
boolean[] memo = new boolean[n + 1];
memo[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = i-1; j >=0 && max_length>=i-j; j--) {
if (memo[j] && wordDict.contains(s.substring(j, i))) {
memo[i] = true;
break;
}
}
}
return memo[n];
}
}