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

139. Word Break(dp)

2016-08-18 23:27 155 查看
题目:

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"
.
查找词典里面的字符串能否组成字符串s。
结题思路:

状态转移方程:

dp[i]=dp[j]&&s(j~i) in dict (0<j<i)

dp[i]表示前i个字符能由词典的词构成。

代码:

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