LC139 单词拆分
题目:给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。
思考:
- 动态规划+set
public class Solution {
/**
* 单词拆分
* 输入: s = "applepenapple", wordDict = ["apple", "pen"]
* 输出: true
* 解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
* 注意,你可以重复使用字典中的单词。
*/
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
// dp[i]:s的前i个字符能否被匹配
boolean[] dp = new boolean[n + 1];
// 空串表示可以被任意单词匹配
dp[0] = true;
// set:[[apple],[pen]]
Set<String> set = new HashSet<>(wordDict);
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && set.contains(s.substring(j, i))) {
dp[i] = true;
// 内存循环只有匹配成功一次,就跳出到外层;开启下一个外层循环
break;
}
}
}
return dp[n];
}
public static void main(String[] args) {
Solution solution = new Solution();
String s = "applepenapple";
List<String> wordDict = new ArrayList<>();
wordDict.add("apple");
wordDict.add("pen");
System.out.println(solution.wordBreak(s, wordDict));
}
}