LeetCode——Word Break
LeetCode——Word Break
Question
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".
Solution
动态规划的思想,从头开始扫描字符串,判断当前子字符串是否可以在字典中查找到,取决于自身以及对这个子字符串的所有划分方式是否可以查找到。
递推关系式子: dp[i] = dp[j] && dp[i - j] (0 <= j <= i)
初始值 dp[0] = true; 表示子字符串长度为0的时候,是可以查找到的。
Answer
public:
bool wordBreak(string s, vector<string>& wordDict) {
if (wordDict.size() == 0 || s.empty())
return false;
vector<int> dp(s.length() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j <= i; j++) {
if (dp[j]) {
// 第二个参数表示,表示从j开始的字符个数
string str1 = s.substr((unsigned int)j, i - j);
if (check(wordDict, str1)) {
dp[i] = true;
break;
}
}
}
}
return dp[s.length()];
}
bool check(vector<string>& wordDict, string& str1) {
for (string str : wordDict)
if (str == str1)
return true;
return false;
}
};