class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> hashSet = new HashSet<>(wordDict);
// 1.确认dp数组, dp[j] 表示长度为j的字符串能否被wordDict中的单词拼接成
boolean[] dp = new boolean[s.length()+1];
// 2.确定递推关系 if(s.substring(i,j)在wordDict中且dp[i]为true的话 dp[j]为true)
// 3.初始化
dp[0] = true;
// 4.遍历顺序 求排列 先遍历背包,再遍历物品
for(int j=1; j<=s.length(); j++){
for(int i=0; i<j; i++){
if(hashSet.contains(s.substring(i,j)) && dp[i]==true){
dp[j] = true;
}
}
}
return dp[s.length()];
}
}
运行结果: