您的位置:首页 > 其它

[leetcode] 139.Word Break

2015-09-01 13:23 411 查看
题目:

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[i]代表的是前i个字符能够通过字典形成。

DP[i] = true; if(DP[j] = true && s.substr(j, i - j) in the dictionary。

以上。

代码如下:

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(s.empty())return true;
vector<bool> DP(s.length() + 1, false);
DP[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 1; j <= i && !DP[i]; j++) {
if(DP[i - j] && wordDict.find(s.substr(i - j, j)) != wordDict.end())DP[i] = true;
}
}
return DP[s.length()];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: