您的位置:首页 > 其它

lintcode:单词切分

2016-03-23 20:10 330 查看
单词切分

给出一个字符串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()];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: