博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[译]单词分割
阅读量:7134 次
发布时间:2019-06-28

本文共 1735 字,大约阅读时间需要 5 分钟。

原文链接:

给定一个字符串s和一个单词字典,确定是否可以将s分割为一个或多个字典单词的空格分隔的序列。

例如:

For example, givens = "leetcode",dict = ["leet", "code"].

因为"leetcode"可以分割为"leet code", 所以返回true.

  1. 普通方法
    这个问题可以用一种简单的方法来解决。讨论总是可以从这个开始。
public class Solution {    public boolean wordBreak(String s, Set
dict) { return wordBreakHelper(s, dict, 0); } public boolean wordBreakHelper(String s, Set
dict, int start){ if(start == s.length()) return true; for(String a: dict){ int len = a.length(); int end = start+len; //end index should be <= string length if(end > s.length()) continue; if(s.substring(start, start+len).equals(a)) if(wordBreakHelper(s, dict, start+len)) return true; } return false; }}

时间是O(n ^ 2)和超过了时间限制。

  1. 动态程序
    利用动态规划方法解决这个问题的关键是:
定义一个数组t[],这样t[i]= =true => 0-(i- 1)可以使用字典进行分段初始状态t[0]= = true
public class Solution {    public boolean wordBreak(String s, Set
dict) { boolean[] t = new boolean[s.length()+1]; t[0] = true; //set first to be true, why? //Because we need initial state for(int i=0; i
s.length()) continue; if(t[end]) continue; if(s.substring(i, end).equals(a)){ t[end] = true; } } } return t[s.length()]; }}

时间:O(字符串长度*字典大小)。

  1. Java解决方案3 -简单高效
    在方案2中, 如果字典的数据量是非常大的, 时间是非常长的.相反,我们可以解决这个问题在O(n ^ 2)时间(n是字符串的长度).
public boolean wordBreak(String s, Set
wordDict) { int[] pos = new int[s.length()+1]; Arrays.fill(pos, -1); pos[0]=0; for(int i=0; i

转载地址:http://autrl.baihongyu.com/

你可能感兴趣的文章
lvs简介和命令
查看>>
RPM 命令详解
查看>>
在Centos7中使用firewall添加端口
查看>>
python 通过threading多线程ssh
查看>>
spark-submit使用及说明
查看>>
jquery验证表单的js代码(HTML+CSS+PHP代码部分省略)
查看>>
Linux学习之CentOS(二十)--CentOS6.4下修改MySQL编码方法
查看>>
我的友情链接
查看>>
手动删除oracle数据库
查看>>
(转)chrome浏览器在各常用移动终端上的User-Agent
查看>>
向Maven本地仓库添加本地jar包
查看>>
Nginx 配置虚拟主机
查看>>
CHI Hair Straightener
查看>>
Redis测试报告
查看>>
邮件归档对安全的整合与提高
查看>>
微信小程序把玩(九)scroll-view组件
查看>>
apache目录访问权限
查看>>
spring MVC配置详解
查看>>
function
查看>>
Easy ×××
查看>>