139. Word Break

Posted

tags:

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

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

##分析##
定义 d[i]表示 0~i子串是否能通过dict中元素表示    
如果存在{str(j,i)∈ dict | j<i } 则d[i]=true    

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

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

139. Word Break

139. Word Break

139. Word Break

139. Word Break

139. Word Break(js)

LeetCode 139. Word Break