LeetCode139——单词拆分
给定一个非空字符串 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 递归加回溯
递归加回溯是我最常用的方法
public boolean wordBreak(String s, List<String> wordDict) {
//1.递归加回溯:超时
Set<String> wordDictSet = new HashSet<>(wordDict) ;
boolean flag = wordBreak(s , wordDictSet , 0) ;
return flag ;
}
private boolean wordBreak(String s, Set<String> wordDictSet, int start) {
boolean flag = false ;
for (int end = start+1 ; end<=s.length() ; end++){
//扫描从start->end 是否有表中包含的数据,如果有就递归,没有继续遍历
if (wordDictSet.contains(s.substring(start,end))){
if (end == s.length()){
return true ;
}
flag = flag || wordBreak(s , wordDictSet , end) ;
}
}
return flag ;
}
2. 优化后的递归加回溯
看到官方给出的优化方案,相当于标记了已经在表中的数据的尾索引。进行记忆化。
public boolean wordBreak(String s, List<String> wordDict) {
//2.优化递归
Set<String> wordDictSet = new HashSet<>(wordDict);
boolean flag = wordBreak(s , wordDictSet , 0 , new Boolean[s.length()+1]) ;
return flag ;
}
private boolean wordBreak(String s, Set<String> wordDictSet, int start, Boolean[] booleans) {
if (start == s.length()){
return true ;
}
if (booleans[start] != null){
return booleans[start] ;
}
for (int end = start + 1 ; end <= s.length() ; end++){
if (wordDictSet.contains(s.substring(start,end)) && wordBreak(s, wordDictSet , end , booleans)){
return booleans[start] = true ;
}
}
return booleans[start] = false ;
}
3. DP——动态规划
解法的主角就是DP
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet = new HashSet<>(wordDict) ;
//有点记忆回溯的原理
boolean[] dp = new boolean[s.length()+1] ;
//0位置
dp[0] = true ;
for (int i=1 ; i<=s.length() ; i++){
for (int j=0 ; j<i ; j++){
if (dp[j] && wordDictSet.contains(s.substring(j , i))){
dp[i] = true ;
break ;
}
}
}
return dp[s.length()] ;
}