一个典型的动态规划题,利用两层循环,遍历所有的子串,当wordDict中含有子串substring(j,i)组成的单词并且上dp数组中对应子串的上一位dp[j] = true时,表明0~i中的所有单词满足拆分要求,因此dp[i] = true。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
int len=Integer.MAX_VALUE;
for(int i=1; i<dp.length; i++){
for(int j=i-1; j>=0; j--){
if(wordDict.contains(s.substring(j,i)) && dp[j]){
dp[i] = true;
break;
}
}
}
return dp[dp.length-1];
}
}