48 lines
1.5 KiB
Java
Raw Normal View History

2025-04-15 11:44:47 +08:00
package dynamic_programming;
2025-07-25 18:23:29 +08:00
import java.util.HashMap;
import java.util.HashSet;
2025-04-15 11:44:47 +08:00
import java.util.List;
/**
* 题目 139. 单词拆分 (wordBreak)
* 描述给你一个字符串 s 和一个字符串列表 wordDict 作为字典如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true
2025-07-25 18:23:29 +08:00
* 注意不要求字典中出现的单词全部都使用并且字典中的单词可以 重复 使用
2025-04-15 11:44:47 +08:00
示例 2
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" "code" 拼接成
* 链接https://leetcode.cn/problems/word-break/
*/
2025-07-25 18:23:29 +08:00
//二刷不会
2025-04-15 11:44:47 +08:00
public class WordBreak {
2025-07-25 18:23:29 +08:00
public boolean wordBreak1(String s, List<String> wordDict) {
int len=s.length();
boolean[] dp=new boolean[len+1];
HashSet<String>set=new HashSet<>(wordDict);
dp[0]=true;
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
dp[i]=dp[i]||dp[j]&&set.contains(s.substring(j,i));
}
}
return dp[len];
}
2025-04-15 11:44:47 +08:00
public boolean wordBreak(String s, List<String> wordDict) {
int total=s.length();
boolean[] dp=new boolean[total+1];
dp[0]=true;
for (int j = 1; j <= total; j++) {
for (String cur : wordDict) {
int cnt = cur.length();
if (j >= cnt)
dp[j] = dp[j] || (dp[j - cnt] && s.substring(j - cnt, j).equals(cur));
}
}
return dp[total];
}
}