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