lintcode:单词切分
2016-03-23 20:10
330 查看
单词切分
给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
样例
s = "lintcode"
dict = ["lint","code"]
返回 true 因为"lintcode"可以被空格切分成"lint code"
解题
DFS
if((s==null ||s.length() ==0) && (dict == null || dict.size()==0))
return true;
95%数据运行超时
动态规划求解
定义数组dp dp[i] =true表示 字符串 s 子串0 - (i-1)在字典中存在
当dp[s.length()] == true 时候表示可以由字典内的单词组成s
给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
样例
s = "lintcode"
dict = ["lint","code"]
返回 true 因为"lintcode"可以被空格切分成"lint code"
解题
DFS
import java.util.Iterator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; // write your code here public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); Main m = new Main(); while(in.hasNext()){ String s = in.nextLine(); String[] str = in.nextLine().split(" "); Set<String> dict = new TreeSet<String>(); for(int i = 0;i<str.length;i++) dict.add(str[i]); int start = 0; boolean flag = m.wordBreak(s, dict, start); System.out.println(flag); } } public boolean wordBreak(String s,Set<String> dict,int start){
if((s==null ||s.length() ==0) && (dict == null || dict.size()==0))
return true;
Iterator it = dict.iterator(); if(start == s.length()) return true; while(it.hasNext()){ String t = (String)it.next(); int end = start + t.length(); if(end > s.length()) continue; if(s.substring(start,end).equals( t )){ if(wordBreak(s,dict,end)){ return true; } } } return false; } }
95%数据运行超时
动态规划求解
定义数组dp dp[i] =true表示 字符串 s 子串0 - (i-1)在字典中存在
当dp[s.length()] == true 时候表示可以由字典内的单词组成s
public class Solution { /** * @param s: A string s * @param dict: A dictionary of words dict */ public boolean wordBreak(String s, Set<String> dict) { // write your code here if((s==null ||s.length() ==0) && (dict == null || dict.size()==0)) return true; return wordBreak(s,dict,0); } public boolean wordBreak(String s,Set<String> dict,int start){ boolean dp[] = new boolean[s.length() + 1]; dp[0] = true;//初始值 for(int i = 0;i<s.length();i++){ if(!dp[i]) continue; for(String t:dict){ int len = t.length(); int end = i+ len; if(end > s.length()) continue; if(s.substring(i,end).equals(t)){ dp[end] = true; } } } return dp[s.length()]; } }
相关文章推荐
- 利用MATLAB绘制隐函数f(x,y)=x^2 * sin(x+y^2)+y^2 * exp(x+y)+5 * cos(x^2+y)=0的曲线
- 通过angularjs的directive以及service来实现的列表页加载排序分页(转)
- 1040. Longest Symmetric String (25)
- Xamarin devexpress datagrid 样式
- linux tar文件解压
- WebView完全解读
- apache配置静态缓存
- imageview wrap_content
- android CheckBox控件的定义及事件监听
- 设计模式之享元模式
- kafka不消费
- Anaconda安装theano出现错误
- 如何编写Linux设备驱动程序
- 类的载入机制
- 类的组合
- 3930: [CQOI2015]选数|递推|数论
- HA高可用集群(双机热备)
- 状态栏iOS
- 在Apache中配置虚拟主机 LAMP
- mac系统卸载okg包命令