LeetCode练习-动态规划算法-word-break

来源:互联网 发布:灵格斯mac版 编辑:程序博客网 时间:2024/05/22 00:08


题目描述

Given a string s and a dictionary of words dict, determine ifs 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".

思路:首先我们要存储的历史信息res[i]是表示到字符串s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。然后假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的表达式。思路是对于每个以i为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的res[j]是不是true,如果都成立,那么res[i]为true,写成式子是

假设总共有n个字符串,并且字典是用HashSet来维护,那么总共需要n次迭代,每次迭代需要一个取子串的O(i)操作,然后检测i个子串,而检测是constant操作。所以总的时间复杂度是O(n^2)(i的累加仍然是n^2量级),而空间复杂度则是字符串的数量,即O(n)。

C++代码如下:

class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        //bool *flag = new bool[s.length() + 1];        deque<bool> res(s.length() + 1, false);        res[0] = true;        int i, j;        for (i = 0; i < s.length(); ++i){            for (j = 0; j <= i; ++j){                bool flag = false;                if(dict.find(s.substr(j, i - j + 1)) != dict.end())//s[j...i]                    flag = true;                if (res[j] && flag){  //s[0...j-1]是否满足条件 && s[j...i]是否满足条件                    res[i + 1] = true;                    break;                }            }        }        return res[s.length()];    }};

本地测试代码:

bool wordBreak(string s, unordered_set<string> &dict);int main(){string s = "LeetCode";unordered_set<string> dict;dict.insert("Leet");dict.insert("Code");cout << wordBreak(s, dict) << endl;return 0;}



参考大神思路:http://blog.csdn.net/linhuanmars/article/details/22358863/

原创粉丝点击