您的位置:首页 > 其它

Leetcode: Word Break

2014-10-31 08:37 260 查看
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"
.
Dynamic Programming: use a boolean array to represent whether the string can be broke from start to that index. Then use the previous status to calculate for the next status. 

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) {
return false;
}

int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}

int size = s.length();
boolean[] canBreak = new boolean[size + 1];
canBreak[0] = true;
for (int i = 1; i <= size; i++) {
canBreak[i] = false;
for (int j = 1; j <= maxLength && j <= i; j++) {
if (canBreak[i - j]) {
String word = s.substring(i - j, i);
if (dict.contains(word)) {
canBreak[i] = true;
break;
}
}
}
}

return canBreak[size];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode