[leetcode][DP] Word Break

来源:互联网 发布:淘宝标着极有家可信吗 编辑:程序博客网 时间:2024/06/10 21:18

题目:

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".

class Solution {public:   bool wordBreak(string s, unordered_set<string>& wordDict) {bool *res = new bool[s.size()];//res[i]表示s的0...i能否word breakmemset(res, false, s.size()*sizeof(bool));for (int i = 0; i < s.size(); ++i){if (wordDict.find(s.substr(0, i+1)) != wordDict.end()){res[i] = true;continue;}for (int j = i-1; j >= 0; --j){//注意j从后往前比从前往后更有效率,因为当后半部分叫短时更有可能匹配单词if (res[j] && wordDict.find(s.substr(j + 1, i-j)) != wordDict.end()){res[i] = true;break;}}}bool ret = res[s.size() - 1];delete[]res;return ret;}};
时间复杂度O(n^2),空间复杂度O(n)


优化算法:table中只放入当前字符之前可以wordBreak的子串的下标,这样减少了无谓的遍历。

class Solution {public:    bool wordBreak(string s, unordered_set<string>& wordDict) {    if(s.empty() || wordDict.empty()) return false;vector<int> table;//table中存放当前字符之前能被wordBreak的子串的下标for (int i = 0; i < s.size(); ++i){string sCur = s.substr(0, i+1);if (wordDict.find(sCur) != wordDict.end()) table.push_back(i);else{for (int j =table.size()-1; j >= 0; --j){int index = table[j];string sWord = s.substr(index + 1, i-index);if (wordDict.find(sWord) != wordDict.end()){table.push_back(i);break;}}}}if(table.size() == 0) return false;return table[table.size() - 1] == s.size()-1;}};


0 0
原创粉丝点击