[动态规划] leetcode 139 Word Break

problem:https://leetcode.com/problems/word-break/

       划分类型问题。

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int n = s.size();
        unordered_set<string> dict;
        for(int i = 0;i < wordDict.size();i++)
        {
            dict.insert(wordDict[i]);
        }
        vector<bool> dp(n + 1, false);
        dp[0] = true;
        for(int i = 0;i < n; i++)
        {
            for(int j = 0;j <= i;j++)
            {
                int len = i - j + 1;
                string word = s.substr(j, len);
       //         cout << word << endl;
                if(dict.find(word) != dict.end())
                {
                    if(dp[j])
                    {
                        dp[i + 1] = true;
                        break;
                    }
                }
            }
        }
        return dp[n];
    }
};

 

posted @ 2019-08-10 00:16  fish1996  阅读(148)  评论(0编辑  收藏  举报