[Leetcode] Word Break I
2015-08-19 15:57
281 查看
Word Break
使用DFS遍历当然是可以的,尝试使用DP应该更加简洁,发现leetcode讨论确实是一个非常不错的资源。
下面是我的改进代码
使用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]; } }
相关文章推荐
- openvz 去掉venet
- c++ primer plus 第八章《编程题8.8.7》
- android休眠之后 定时任务TimerTask不生效
- 反射的详解与使用
- grep命令常用的15招
- HNOI 2002 营业额统计
- Java内存泄露例子
- 1095. Cars on Campus (30)
- 学习笔记之树的镜像
- 腾讯电面——C/C++基础之关键字
- 退出指南(4) - 如何选择一个公司
- 问题: ActivityManager: Warning: Activity not started, its current task has been brought to the front
- IOS第11天(2:UIPickerView自定义国旗选择)
- Csharp: read excel file using Open XML SDK 2.5
- 使用Kettle抽取MongoDB数据到Oracle
- hdu 1405
- c++ primer plus 第八章《编程题8.8.5》
- 小P的故事——神奇的换零钱
- (转载)KL距离
- 动态计算cell高度(1)