您的位置:首页 > 其它

LeetCode: Word Break

2015-03-17 12:38 239 查看
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。dp[i]表示前i个字符可以被word break。所以可以得到状态转移方程:dp[i] = dp[j] && dict.contains(s[j ~ i])

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
StringBuilder sb = new StringBuilder();
boolean[] can = new boolean[s.length() + 1];
can[0] = true;
for(int i = 1; i < can.length; i++){
for(int j = 0; j < i; j++){
can[i] |= can[j] && dict.contains(s.substring(j, i));
}
}
return can[s.length()];
}
}


这里还可以预处理优化下,先O(n)扫一遍得出字典中最短和最长单词的长度。每次分割只选取[min, max]长度之间的substring。

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(String str : dict){
min = Math.min(str.length(), min);
max = Math.max(str.length(), max);
}
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 0; i <= s.length() - min; i++){
for(int k = min; k <= max && i + k <= s.length(); k++){
if(dp[i + k] || !dp[i]){
continue;
}
dp[i + k] = dp[i] && dict.contains(s.substring(i, i + k));
}
}
return dp[s.length()];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode