您的位置:首页 > 其它

leetcode -- Word Break

2013-10-08 14:23 330 查看
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"
.

[解题思路]

1.brute force will TLE.

just check every substring from index 0 to the end.

public boolean wordBreak(String s, Set<String> dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int len = s.length();
boolean flag = false;

for(int i = 1; i <= len; i++){
String subStr = s.substring(0, i);
if(dict.contains(subStr)){
if(subStr.length() == s.length()){
return true;
}
flag = wordBreak(s.substring(i), dict);
}
}
return flag;
}


2.DP

Reference the dicussion in leetcode.

Here we use seg(i, j) to demonstrate whether substring start from i and length is j is in dict?

base case:

when j = 0; seg(i, j) = false;

State transform equation:

seg(i, j) = true. if s.substring(i, j - 1) is in dict.

else seg(i, j) = seg(i, k) && seg(i + k, j - k);

public boolean wordBreak(String s, Set<String> dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(s == null || dict.size() <= 0){
return false;
}

int length = s.length();
// seg(i, j) means substring t start from i and length is j can be segmented into
// dictionary words
boolean[][] seg = new boolean[length][length + 1];
for(int len = 1; len <= length; len++){
for(int i = 0; i < length; i++){
String t = s.substring(i, i + len);
if(dict.contains(t)){
seg[i][len] = true;
continue;
}
for(int k = 1; k < len; k++){
if(seg[i][k] && seg[i+k][len-k]){
seg[i][len] = true;
break;
}
}
}
}
return seg[0][length];
}


这题貌似是一道面试题:http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: