单词切分

给出一个字符串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

至于为什么?

自己根据输出发现:当有一个字符没有出现,后面的将都会为false,一次没有找到,破坏了后面的继续查找字符串的长度,后面就再也找不到,最后一个位置为false

自己测试

    public static void main(String[] args){
Solution s = new Solution();
Set<String> dict = new HashSet<String>();
String str = "123";
dict.add("1");
dict.add("2"); dict.add("64");
System.out.println(s.wordBreak(str, dict));
dict.add("3");
System.out.println(s.wordBreak(str, dict));
}

输出

[true, false, false, false]
[true, true, false, false]
[true, true, true, false]
[true, true, true, false]
false
[true, false, false, false]
[true, true, false, false]
[true, true, true, false]
[true, true, true, true]
true
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()];
} }

lintcode:单词切分的更多相关文章

  1. Lintcode--009(单词切分)

    http://www.lintcode.com/zh-cn/problem/word-break/ 单词切分 给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词. ...

  2. lintcode :单词搜索

    题目 单词搜索 给出一个二维的字母板和一个单词,寻找字母板网格中是否存在这个单词. 单词可以由按顺序的相邻单元的字母组成,其中相邻单元指的是水平或者垂直方向相邻.每个单元中的字母最多只能使用一次. 样 ...

  3. word break II(单词切分)

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add space ...

  4. lintcode 单词接龙II

    题意 给出两个单词(start和end)和一个字典,找出所有从start到end的最短转换序列 比如: 1.每次只能改变一个字母. 2.变换过程中的中间单词必须在字典中出现. 注意事项 所有单词具有相 ...

  5. (lintcode全部题目解答之)九章算法之算法班题目全解(附容易犯的错误)

    --------------------------------------------------------------- 本文使用方法:所有题目,只需要把标题输入lintcode就能找到.主要是 ...

  6. leetcode & lintcode for bug-free

    刷题备忘录,for bug-free leetcode 396. Rotate Function 题意: Given an array of integers A and let n to be it ...

  7. leetcode & lintcode 题解

    刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...

  8. lintcode 题目记录3

    Expression Expand  Word Break II Partition Equal Subset Sum  Expression Expand  字符串展开问题,按照[]前的数字展开字符 ...

  9. Eclipse上运行第一个Hadoop实例 - WordCount(单词统计程序)

    需求 计算出文件中每个单词的频数.要求输出结果按照单词的字母顺序进行排序.每个单词和其频数占一行,单词和频数之间有间隔. 比如,输入两个文件,其一内容如下: hello world hello had ...

随机推荐

  1. SQL Server数据库学习笔记-三大范式

    第一范式(First Normal Form,简称1NF):数据库表中的字段都是单一属性的,不可再分.这个单一属性由基本类型构成,包括整型.实数.字符型.逻辑型.日期型等.要求一个属性只包含一个值,多 ...

  2. angularJS项目-ajax事件的按钮loading和页面loading状态 & Controller之间通信-待续

    1).按钮loading --TODO 2). page loading状态 1.在module中注入指令 // Route State Load Spinner(used on page or co ...

  3. Json.Net使用JSON Schema验证JSON格式

    Json.NET supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. It s ...

  4. 给Eclipse提速的7个技巧(转)

    本文由 ImportNew - 孙 波翔 翻译自 nicolasbize.欢迎加入翻译小组.转载请参见文章末尾的要求. 大约一个月前,我发表了一篇博客,其中介绍了对Eclipse的爱与恨. 有些人问我 ...

  5. 状压DP

    今天稍微看了下状压DP,大概就是这样子的,最主要的就是位运算, i and (1<<k)=0 意味着i状态下没有 k : i and (1<<k)>0 意味着i状态下有 ...

  6. Why does uitableview cell remain highlighted?

    What would cause a tableview cell to remain highlighted after being touched? I click the cell and ca ...

  7. background-clip

    background-clip 用来将背景图片做适当的裁剪以适应实际需要. 语法: background-clip : border-box | padding-box | content-box | ...

  8. django构建blog--页面部分(eclipse+pydev)

    本文介绍的是在eclipse+pydev 平台下,利用django 搭建blog的第2部分:页面部分(主要涉及3个部分:模板.视图.URL模式) 篇幅1:创建模板 blog目录下新建一个文件夹:tem ...

  9. boost之mutex scoped_lock

    1.boost里的互斥量类型由mutex表示. 代码示例: #include <iostream> #include <string> #include <vector& ...

  10. 项目分析(PLUG)

    plug过程 .INIT_PLUG #define INIT_PLUG Plug::InitPlug g_InitPlug(true); //共享内存数据结构 struct PlugShareMemo ...