您的位置:首页 > 其它

LeetCode 139. Word Break (Medium)

2017-09-13 22:50 288 查看

题目描述:

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.

Example:

s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".


题目大意:给出一个字符串,给出一个字符串数组(字典),问字符串是否能分解为字典里的字符串。

思路:暴力做法当然是遍历所有子字符串组合,显然时间复杂度太高。从网上看到可以动态规划,学习了一下。大概思路是:假如前i个字符可以切分(由字典的字符串组成),那看看前i - j个字符能否被切分,如果可以就继续。复杂度貌似是O(n^2)。

c++代码:

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