32 lines
1.1 KiB
Java
32 lines
1.1 KiB
Java
|
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];
|
|||
|
}
|
|||
|
}
|