您的位置:首页 > 其它

[Leetcode] Word Break I

2015-08-19 15:57 281 查看
Word Break

使用DFS遍历当然是可以的,尝试使用DP应该更加简洁,发现leetcode讨论确实是一个非常不错的资源。

下面是我的改进代码

public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if(s==null||s.length()==0) return false;
//flag[i] represents if s[0,...,i] can be formed by the wordDict
boolean [] flag = new boolean[s.length()];
for(int i=0;i<s.length();i++){//i is the end index
for(int j=i;j>=0;j--){//我觉得从后往前更加合理,因为一般word不会太长吧,但是不知为什么,速度没有太高的提升
//for(int j=0;j<=i;j++){
String subword = s.substring(j,i+1);
if(wordDict.contains(subword)&&(j==0||flag[j-1]))
{
flag[i]=true;
break;//如果找到了一种划分方式,就可以结束了
}
}
}
return flag[s.length()-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: