leetcode 139. Word Break
题目
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
递推公式如下:
考虑 string 的前 n 个字符,对于第 i 个字符( i 包含于 [0, n) ),如果在 DP 表 table 中, table[i] 的取值为真,并且 [i,n) 也是字典中的单词,那么 [0,n) 的结果就为真。
代码
bool wordBreak(const string s, const unordered_set<string>& wordDict) {
vector<bool> table(s.size() + 1, false); //DP表,用来存储前驱结点的解
table[0] = true;
for (string::size_type end = 0; end < s.size(); end++) {
for (string::size_type beg = 0; beg <= end; beg++) {
string temp = s.substr(beg, end - beg + 1);
bool prev = table[beg];
if (prev && wordDict.find(temp) != wordDict.cend()) {
table[end + 1] = true;
break;
}
}
}
return table[s.size()];
}
智慧在街市上呼喊,在宽阔处发声。