判断存不存在解比找出解容易,但思路是一致的,都使用了memorize来存放搜索结果
public class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return backws(s,wordDict,new HashMap<String,Boolean>());
}
// dfs
private boolean backws(String s, List<String> wordDict,
HashMap<String, Boolean> map) {
if(map.containsKey(s)) return map.get(s);
boolean res = false;
for(String word: wordDict){
if(s.startsWith(word)){
if(word.length()==s.length()) {
res = true;
}
else{
res = backws(s.substring(word.length()),wordDict,map);
}
if(res) break;
}
}
map.put(s, res);
return res;
}
}
本文介绍了一种解决 LeetCode 上经典题目 Word Break 的方法。该方法通过递归深度优先搜索 (DFS) 并利用哈希映射进行备忘录优化,有效地判断给定字符串是否能由字典中的单词组成。

1278

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



