题目
链接
题解
import java.util.HashSet;
import java.util.Set;
class Solution {
// 动态规划 dp[i] 存储1到i字符串是否能够字典匹配,s[j..i]表示从j到i的字符串
// 转移方程:dp[i] = dp[j] && dictMatch(s[j..i])
public boolean wordBreak(String s, List<String> wordDict) {
// 字典转换成哈希表
Set<String> dic = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dic.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}