力扣-12.18-139
作者:互联网
类似第322题的第一种方法:
外层循环是背包,内层循环是物品,需要注意的是和前几题不一样
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len = s.length();
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for(int i = 1; i <= len; i++){
for(int j = 0; j < i; j++){
if(dp[j] && wordDict.contains(s.substring(j, i))){
dp[i] = true;
}
}
}
return dp[len];
}
}
另一种写法:
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len = s.length();
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for(int i = 1; i <= len; i++){
for(String word : wordDict){
int l = word.length();
if(l <= i && word.equals(s.substring(i - l, i))){
dp[i] = dp[i - l] || dp[i];
}
}
}
return dp[len];
}
}
在求 dp[i] 的时候需要和 dp[i] 进行与操作而不直接写成
dp[i] = dp[i - l];
的原因是可能前面的单词已经可以满足要求,将 dp[i] 设置为true了,但是之后的单词不满足要求,又将其设置为false了,或者可以像下面这样写:
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len = s.length();
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for(int i = 1; i <= len; i++){
for(String word : wordDict){
int l = word.length();
if(l <= i && word.equals(s.substring(i - l, i))){
dp[i] = dp[i - l];
}
if(dp[i] == true){
break;
}
}
}
return dp[len];
}
}
标签:int,len,力扣,boolean,wordDict,139,true,dp,12.18 来源: https://blog.csdn.net/Desperate_gh/article/details/111396398