lintcode--单词划分
来源:互联网 发布:软件调试什么意思 编辑:程序博客网 时间:2024/06/16 12:49
给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
给出
s = "lintcode"
dict = ["lint","code"]
返回 true 因为"lintcode"可以被空格切分成"lint code"
/*
/动态规划
解题思路:
s = lintcode 可以分为l和intcode,若是l是可分割单词,并且intcode单词在dict中,
表示s也是可分割单词。若不符合,s = lintcode可以分为li和ntcode,若是li是可分割单词,
并且ntcode单词在dict中,则表示s也是可分割单词。
...
同理得出BWord[ n ]表示字符串Str[0,n]是否是可分割单词,是则为true,否为false。
BWord[ n ] = BWord[ i ] && Str[ i+1 ,n ]在dict中
动态规划求解
定义数组dp dp[i] =true表示 字符串str子串0 - (i-1)在字典中存在(可分割)
当dp[s.length()] == true 时候表示可以由字典内的单词组成s
至于为什么?
自己根据输出发现:当有一个字符没有出现,后面的将都会为false,一次没有找到,
破坏了后面的继续查找字符串的长度,后面就再也找不到,最后一个位置为false
*/
public class Solution {
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] != true){
//下一个循环
continue;
}
//遍历字典中字符串
for(String t:dict){
int len = t.length();//字典每个字符串的长度
int end = i+ len;//str中的结尾len
if(end > s.length())
continue;
//整体比较一样的长度
if(s.substring(i,end).equals(t)){
dp[end] = true;
}
}
}
return dp[s.length()];
}
}
- lintcode--单词划分
- LintCode-数组划分
- LintCode 数组划分
- LintCode-链表划分
- LintCode:数组划分
- LintCode 数组划分
- lintcode之数组划分
- LintCode:数组划分
- LintCode:链表划分
- 【LintCode】数组划分
- Lintcode 链表划分
- Lintcode 数组划分
- LintCode 链表划分
- 链表划分-LintCode
- LintCode : 链表划分
- LintCode 31 数组划分
- 数组划分--lintcode
- 链表划分-LintCode
- 链表面试题之判断链表是否带环?若带环求环的长度?若带环求环的入口点?
- Ubuntu防火墙安装和配置
- pat-a1072. Gas Station (30)
- Zephyr程序初探(1):LED程序及调试过程
- lowbit
- lintcode--单词划分
- 百度2017春招笔试真题编程题集合--寻找三角形
- 欢迎使用CSDN-markdown编辑器
- PAT 乙级 1003.我要通过!(20)
- 自己的python 学习笔记
- (88)将系统属性输出到文件中Properties.list方法
- Eigen 库的配置
- EXCEL排序(sort结构体排序)
- 安装使用celery异步任务