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()]; } };
相关文章推荐
- Leetcode 139. Word Break (Medium) (cpp)
- [Leetcode 139, medium] Word Break
- leetcode 139. Word Break
- LeetCode 139 Word Break (DFS 分词 解存在性判断)
- 139 Word Break [Leetcode]
- 【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】
- 【Leetcode】139. Word Break
- Leetcode 139, Word Break
- leetcode[139]Word Break
- LeetCode 139. Word Break
- 【Medium】139. Word Break
- LeetCode139:Word Break
- 139. Word Break -Medium
- Leetcode 139 Word Break
- [leetcode 139]Word Break
- Leetcode 139 Word Break
- leetcode 139: Word Break
- LeetCode139:Word Break
- LeetCode 139 Word Break
- LeetCode 139. Word Break