LeetCode139. Word Break
2017-10-21 16:02
190 查看
LeetCode139.Word_Break
题目: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.
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
题目分析:
这道题是一道关于动态规划的题目。刚开始的时候我也没有理解如何用动态规划去做,那时候刷面试题的时候刷到这道题,花了一个小时也不会做,然后上网查的时候才发现这道题出自LeetCode,然后才发现是通过动态规划去做。
令 dp[i] = 0 - i的字符串可以在字典中找到相应的字符串。
代码:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
std::vector<bool> dp(s.size()+1,0);
dp[0] = 1;
for (int i = 1; i <= s.size(); 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] = 1;
}
}
}
return dp[s.size()];
}
};
相关文章推荐
- (Java) LeetCode 139. Word Break —— 单词拆分
- leetcode 139. Word Break 深度优先遍历DFS按照index递归搜索 + 很棒的动态规划DP做法
- [leetcode] 139. Word Break 解题报告
- LeetCode 139. Word Break 动态规划DP Python解法
- [Leetcode] 139. Word Break 解题报告
- 【LeetCode】139. Word Break 解题报告
- 【算法作业16】LeetCode 343. Integer Break
- Leetcode中字符串与break(一)
- leetCode Word Break解题分享
- LeetCode Word Break
- 343. Integer Break(LeetCode, C++, 动态规划)
- LeetCode - Word Break II
- [LeetCode] WordBreak II, Solution
- leetcode之Word Break II
- Leetcode-Word Break II
- leetcode-140-Word Break II
- LeetCode Word Break
- [LeetCode] Word Break II
- Leetcode 343 Integer Break
- Leetcode Word Break II