139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

解题思路:一开始使用了暴力搜索,显而易见的,TLE了。

class Solution {
public:
    bool helper(string s,set<string>&wordDicts){
        if(s.empty())return true;
        if(hash[s])return hash[s];
        for(int i=1;i<=s.length();i++){
           // cout<<s.substr(0,i)<<endl;
            if(wordDicts.find(s.substr(0,i))!=wordDicts.end()&&helper(s.substr(i),wordDicts)){
                return true;
            }
        }
        return false;
    }
    bool wordBreak(string s, vector<string>& wordDict) {
        set<string>wordDicts(wordDict.begin(),wordDict.end());
        return helper(s,wordDicts);
    }
};

正确解法:dp[i]表示从开始到i这个位置的字符串是否能由集合中的单词拼接而成。

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

 

posted @ 2017-09-29 14:39  Tsunami_lj  阅读(114)  评论(0编辑  收藏  举报