Medium
这道题之前一刷用的dfs做,现在又不会那个方法了,说明我dfs真的弱,现在用dp做一下. 这里dp[i]表示s.substring(0, i)是否满足要求.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
if (s == null || s.length() == 0){
return true;
}
//dp[i] stands for whether s.substring(0, i) could be segmented into a one or more dictionary words.
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] && wordDict.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}