一个典型的动态规划题,利用两层循环,遍历所有的子串,当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];
}
}
本文介绍了一种使用动态规划算法解决单词拆分问题的方法。通过两层循环遍历所有子串,检查是否存在于词典中,同时利用dp数组记录状态,实现高效判断。关键在于理解dp数组的含义及更新策略。
1725

被折叠的 条评论
为什么被折叠?



