[leetcode] 139. Word Break 解题报告

来源:互联网 发布:obs是什么软件 编辑:程序博客网 时间:2024/06/05 01:51

题目链接:https://leetcode.com/problems/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".


思路: 一个比较直观的想法是DFS, 但是需要注意的是要记录搜索过的状态, 不然会超时.

代码如下:

class Solution {public:    bool DFS(string& s, unordered_set<string>& wordDict, int k)    {        if(k == s.size()) return true;        if(hash.count(k)) return hash[k];        for(int i = k; i < s.size(); i++)        {            string str = s.substr(k, i-k+1);            if(!wordDict.count(str)) continue;            bool ans = DFS(s, wordDict, i+1);            hash[i+1] = ans;            if(ans == true) return true;        }        return false;    }        bool wordBreak(string s, unordered_set<string>& wordDict) {        return DFS(s, wordDict, 0);    }unordered_map<int, bool> hash;};

参照http://fisherlei.blogspot.com/2013/11/leetcode-word-break-solution.html 这里的方法重新写了一个。

还有一种思路应该是自底上下dp搜索,用dp数组记录状态,记录每一位之前的字串是否可以由字典构成

如果s的一个子串是否可以由字典子集构成有三种情况

1. 如果子串本身就在字典中,则可以

2. 如果字串可以存在一个k使得之前的字串是可以由字典构成,k到i的字串存在在字典中,则此字串也是可以由字典构成的

3. 如果上述两种情况都不成立,则说明这个字串不可以由字典构成

这样遍历到最后就可以得到最后一位是否可以由字典构成。时间复杂度为O(n*n), 空间复杂度为O(n)

具体代码如下:

class Solution {public:    bool wordBreak(string s, unordered_set<string>& wordDict) {        int len = s.size();        vector<int> dp(len+1, 0);        dp[len] = 1;        for(int i = len-1; i >= 0; i--)        {            string substr;            for(int j = i; j < len; j++)            {                substr += s[j];                if(wordDict.count(substr) && dp[j+1]) dp[i] = 1;            }        }        return dp[0];    }};


0 0
原创粉丝点击