您的位置:首页 > 其它

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 = 
"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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string