package dynamic_programming; import java.util.HashMap; import java.util.HashSet; 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 wordBreak1(String s, List wordDict) { int len=s.length(); boolean[] dp=new boolean[len+1]; HashSetset=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]; } public boolean wordBreak(String s, List 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]; } }