LeetCode-139-单词拆分

思路
本题考虑使用动态规划来解决,对于每个子串S[0…i],可以考察S[0…j]和S[j…i]是否存在于词典中,也就是dp[i]=dp[j]&&set.contains(s[j…i])
代码
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len=s.length();
Set<String> set = new HashSet(wordDict);
boolean []dp=new boolean[len+1];
dp[0]=true;
for(int i=1;i<=len;i++){
for(int j=0;j<i;j++){
if(dp[j]&&set.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[len];
}
}
优化:每次并不需要从s[0]开始搜索。因为wordDict中的字符串长度是有限的。只需要从i-maxlen开始搜索就可以了,因此先求出最大长度maxlen
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int len=s.length();
Set<String> set = new HashSet(wordDict);
boolean []dp=new boolean[len+1];
dp[0]=true;
int maxlen=0;//求出词典中单词的最大长度
for(String ss:set){
maxlen=Math.max(maxlen,ss.length());
}
for(int i=1;i<=len;i++){
//每次并不需要从s[0]开始搜索。因为wordDict中的字符串长度是有限的。
//只需要从i-maxlen开始搜索就可以了
for(int j=Math.max(0,i-maxlen);j<i;j++){
if(dp[j]&&set.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[len];
}
}
这篇博客详细介绍了如何使用动态规划解决LeetCode上的139题——单词拆分问题。作者首先展示了基本的动态规划实现,然后通过优化减少了搜索的范围,提高了算法效率。博客内容深入浅出,适合学习动态规划和算法优化的读者。
1115

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



