您的位置:首页 > 其它

leetcode 139. Word Break

2016-06-18 14:23 260 查看

题目

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()];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: