Leetcode 139.单词拆分
题目链接
思路:完全背包问题,有顺序要求,先遍历背包,再遍历物品
代码:
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// 完全背包,有顺序要求,所以先遍历背包,再遍历物品
Set<String> set = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i <= s.length(); i++) {
for (int j = 0; j < i && !dp[i]; j++) {
if (set.contains(s.substring(j, i)) && dp[j]) {
dp[i] = true;
}
}
}
return dp[s.length()];
}
}