139. 单词拆分
题目描述
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例1:
输入:s="leetcode",wordDict=["leet","code"]s = "leetcode", wordDict = ["leet", "code"]s="leetcode",wordDict=["leet","code"]
输出:truetruetrue
示例2:
输入:s="applepenapple",wordDict=["apple","pen"]s = "applepenapple", wordDict = ["apple", "pen"]s="applepenapple",wordDict=["apple","pen"]
输出:truetruetrue
示例3:
输入:s="catsandog",wordDict=["cats","dog","sand","and","cat"]s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]s="catsandog",wordDict=["cats","dog","sand","and","cat"]
输出:falsefalsefalse
思路
本题初初看说实话,完全没看出动态规划的感觉。甚至觉得优点像kmp有点像回溯。
思路1:动态规划
1、dp[i]表示字符串长度为i时,若dp[i]为true,则表示可以拆分为一个或多个在字典中出现的单词。
2、if([j,i]这个区间的字串出现在字典里且dp[j]为true),则dp[i]为true
3、本题在求能够组成时对顺序是有要求的,故而是排列问题。
思路2:回溯法
解法1
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>(wordDict);
boolean[] valid = new boolean[s.length()+1];
valid[0] = true;
for(int i = 1;i<=s.length();i++){
for(int j = 0;j<i && !valid[i];j++){
if(set.contains(s.substring(j,i)) && valid[j]){
valid[i] = true;
}
}
}
return valid[s.length()];
}
}
解法2
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i = 1;i<=s.length();i++){
for(String word : wordDict){
int len = word.length();
if(i >= len && dp[i-len] && word.equals(s.substring(i-len,i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
解法3
class Solution {
public Set<String> set;
public int[] memo;
public boolean wordBreak(String s, List<String> wordDict) {
memo = new int[s.length()];
set = new HashSet<>(wordDict);
return helper(s,0);
}
public boolean helper(String s, int startIndex){
if(startIndex == s.length()){
return true;
}
if(memo[startIndex] == -1){
return false;
}
for(int i = startIndex;i<s.length();i++){
String sub = s.substring(startIndex,i+1);
if(!set.contains(sub)){
continue;
}
boolean res = helper(s,i+1);
if(res){
return true;
}
}
memo[startIndex] = -1;
return false;
}
}
总结
背包问题今天开始就完结了,有一些规律和题型已经大概有些感觉了,再多练几次,我觉得还是有希望的。
文章讲述了如何判断一个字符串是否能由给定字典中的单词拼接而成。提出了动态规划和回溯法两种解决方案,其中动态规划通过构建布尔数组记录字符串的可分解状态,而回溯法则通过递归尝试所有可能的单词分割来找出答案。文章提供了具体的代码实现,并指出这类问题与背包问题有一定的关联性。

被折叠的 条评论
为什么被折叠?



