Day46题目
今天是背包问题的收官
LeetCode139单词划分
核心思想:背包问题最难的就是判断遍历的i和j分别代表什么,如何更新dp数组.这道题目的dp数组是valid,i表示容量s的长度(这个我想到了),j没有用来遍历单词数组,而是用来遍历当前长度i下,合格的部分.是否在单词数组中,使用了set的contains判断.自己想肯定想不了这么好的方法.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>(wordDict);
boolean[] valid = new boolean[s.length()+1];
valid[0] = true;
for(int i = 0 ; i <= s.length(); i ++){
for(int j = 0 ; j < i && !valid[i] ; j ++){
if(set.contains(s.substring(j,i)) && valid[j]){
valid[i] = true;
}
}
}
return valid[s.length()];
}
}
1544



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



