32 lines
1.1 KiB
Java
Raw Normal View History

2025-04-15 11:44:47 +08:00
package dynamic_programming;
import java.util.List;
/**
* 题目 139. 单词拆分 (wordBreak)
* 描述给你一个字符串 s 和一个字符串列表 wordDict 作为字典如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true
* 注意不要求字典中出现的单词全部都使用并且字典中的单词可以重复使用
示例 2
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" "code" 拼接成
* 链接https://leetcode.cn/problems/word-break/
*/
public class WordBreak {
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];
}
}