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

[Leetcode][JAVA] Word Break

2014-10-13 23:42 344 查看
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会比较效率地解决此问题。基本思想是: 如果S能被分割,那么存在某个位置i,使得S(0,i)能被分割且S(i+1,end)在字典里。需要双重循环,第一重循环取出子串S(0,k) (k=1,2,....end). 第二重循环在S(0,k)中判断每一个位置j是否满足S(0,j)可分割,且S(j+1,k)在字典里,如果找到满足条件的位置则跳出这重循环。

考虑到捕获到第一个单词时,S(0,j)状态还不存在,所以可以在dp数组第一位放置状态true,如此得到第一个单词时考察S(0,0)得到true,且剩余部分在字典里,满足条件,将相应dp位置为true.

代码:

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