[LeetCode] 139 Word Break

Posted fengzw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 139 Word Break相关的知识,希望对你有一定的参考价值。

原题地址:

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

 

题目:

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

 

解法:

这道题目利用动态规划做出来,不得不说想法是很巧妙的,我也是参考了网上的代码才AC了。因此,先放代码,等我完全弄懂再补充吧:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        if(s == "" || s.size() == 0) {
            return true; 
        }
        unordered_map<int, bool> res;
        for (int i = 0; i <= s.size(); i++) {
            res[i] = false;
        }
        res[0] = true;
        for (int i = 0; i < s.size(); i++) {
            string str = s.substr(0, i + 1);
            for (int j = 0; j <= i; j++) {
                if (res[j] && find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) {
                    res[i + 1] = true;
                    break;
                }
                str = str.substr(1, str.size() - 1);
            }
        }
        return res[s.size()];
    }
};

 



以上是关于[LeetCode] 139 Word Break的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 139 Word Break

LeetCode #139. Word Break C#

Leetcode 139. Word Break

LeetCode 139: Word Break

leetcode 139. Word Break

LeetCode-139-Word Break