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()];
}
};