class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
//动态规划 s[i]以i结尾的子串是否满足题干条件
boolean [] dp=new boolean[s.length()];
Set<String> set1=new HashSet();
//把worddict放到字典中
for(String str:wordDict){
set1.add(str);
}
for(int r=0;r<s.length();r++){
if(set1.contains(s.substring(0,r+1))){
dp[r]=true;
continue;
}
for(int j=0;j<r;j++){
if(dp[j]&&set1.contains(s.substring(j+1,r+1))){
dp[r]=true;
break;
}
}
}
return dp[s.length()-1];
}
}
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet=new HashSet(wordDict);
boolean[] dp = new boolean[s.length() + 1]; //dp[i] 表示以第i个字符结尾的字符串是否符合要求
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
//第 j 个字符的子串和第 j 到 i 的子串都符合要求,返回true
if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}