LeetCode 139 Word Break
2016-08-09 00:23
423 查看
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s =
dict =
Return true because
方法一:dp . Runtime: 12
ms beats 37.55% of javasubmissions.
public boolean wordBreak2(String s, Set<String> wordDict) {
int len = s.length();
boolean[] valid = new boolean[len + 1];
valid[0] = true;
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
if (valid[j] && wordDict.contains(s.substring(j, i))) {
valid[i] = true;//valid[i]表示s的前i个字符能不能被dict完美划分
break;
}
}
}
return valid[len];
}
方法二:回溯。Runtime: 10 ms beats 72.27% of javasubmissions.
Map<Integer, Boolean> isBreakable = new HashMap<>(); // can we break substring( beginIndex ) ?
public boolean wordBreak(String s, Set<String> wordDict) {
if (s.equals("")) return true;
for (int i = 1; i <= s.length(); ++i) {
if (wordDict.contains(s.substring(0, i))) {
Boolean result = isBreakable.get(i);
if (result == null) {
result = wordBreak(s.substring(i), wordDict);
isBreakable.put(i, result);
}
if (result) return true;
}
}
return false;
}
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
方法一:dp . Runtime: 12
ms beats 37.55% of javasubmissions.
public boolean wordBreak2(String s, Set<String> wordDict) {
int len = s.length();
boolean[] valid = new boolean[len + 1];
valid[0] = true;
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
if (valid[j] && wordDict.contains(s.substring(j, i))) {
valid[i] = true;//valid[i]表示s的前i个字符能不能被dict完美划分
break;
}
}
}
return valid[len];
}
方法二:回溯。Runtime: 10 ms beats 72.27% of javasubmissions.
Map<Integer, Boolean> isBreakable = new HashMap<>(); // can we break substring( beginIndex ) ?
public boolean wordBreak(String s, Set<String> wordDict) {
if (s.equals("")) return true;
for (int i = 1; i <= s.length(); ++i) {
if (wordDict.contains(s.substring(0, i))) {
Boolean result = isBreakable.get(i);
if (result == null) {
result = wordBreak(s.substring(i), wordDict);
isBreakable.put(i, result);
}
if (result) return true;
}
}
return false;
}
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- android上改变listView的选中颜色
- String.intern
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- Redis02 使用Redis数据库(String类型)全面解析
- PostgreSQL ERROR: invalid escape string 解决办法
- C#中Byte[]和String之间转换的方法
- 浅谈C++中的string 类型占几个字节
- 标准C++类string的Copy-On-Write技术
- C++实现string存取二进制数据的方法
- 关于C++ string和c类型字符数组的对比
- C#中string和StingBuilder内存中的区别实例分析
- 详解C++中实现继承string类的MyString类的步骤
- PHP STRING 陷阱原理说明
- c#中 String和string的区别介绍
- C#实现的图片、string相互转换类分享
- asp.net String.IsNullOrEmpty 方法