您的位置:首页 > 编程语言 > Java开发

LeetCode-139. Word Break (JAVA)单词切分

2017-05-14 21:46 447 查看

139. Word Break

Given a non-empty string s and a dictionary
wordDict containing a list of non-empty words, determine if
s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s =
"leetcode"
,
dict =
["leet", "code"]
.

Return true because
"leetcode"
can be segmented as
"leet code"
.

UPDATE (2017/1/4):

The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

单词拆分问题,典型的动态规划

设dp[i]为前i个字符是否可以切割。

一个字符串S,它的长度为len,如果S能够被“字典集合”(dict)中的单词拼接而成,那么所要满足的条件为:

dp[j] && dict.contains(s.substring(j, i))

如果我们想知道某个子串是否可由dict中的几个单词拼接而成就可以用这样的方式得到结果(满足条件为True, 不满足条件为False)存入到一个boolean数组的对应位置上

DP(动态规划)

//dict中的单词可以重复使用
public boolean wordBreak(String s, List<String> dict) {
int len = s.length();
//len+1
//dp[i]表示前i个字符能不能被dict完美划分
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for (int i = 1; i <= len; i++)
for (int j = 0; j < i; j++) {
// 注意substring是前闭后开
String tmp = s.substring(j, i);
//能否组合出f[i]表示的子串,k表示组合中前半段的
if (dp[j] && dict.contains(tmp)) {
dp[i] = true;
break;
}
}
return dp[len];

}使用BFS
和DP的思想一样

注意使用set去重,不然TLE
public boolean wordBreak(String s, List<String> dict) {
if (dict.contains(s))
return true;
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(0);
//使用set去检查去除重复计算
//这是是时间复杂度降到O(N^2)的关键
Set<Integer> visited = new HashSet<Integer>();
visited.add(0);
while (!queue.isEmpty()) {
int curIdx = queue.poll();
for (int i = curIdx + 1; i <= s.length(); i++) {
if (visited.contains(i))
continue;
if (dict.contains(s.substring(curIdx, i))) {
//如果到达中重点,
//注意此时的i是curIdx + 1
if (i == s.length())
return true;
queue.offer(i);
visited.add(i);
}
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息