Leetcode-Word Break II

来源:互联网 发布:枪林弹雨免费刷枪软件 编辑:程序博客网 时间:2024/04/30 11:03

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].

A solution is [“cats and dog”, “cat sand dog”].
题意:对于一个字符串和给定字典,给出字符串由字典中字符组成的所有可能结果。
DP,类似前面提到的Work Break,这里标志位变为二维的,map< int,vector < string > > dp1,int存放字符在s中的位置,vector则存放改字符之前的所有可能string组合方式。
步骤:
对于s中(0,i)的字符串,判断是否在字典中,若在,则将其加入dp1[i]中,若不存在,则对j(j >= 1 && j < i),若dp1[j].size()>0,判断(j,i)之间的字符串是否在字典中,若存在,则将其附着在dp[j]中字符串之后。

vector<string> wordBreak(string s, unordered_set<string>& wordDict) {    map<int,vector<string>> dp1;    if(s.length()==0)    {        return vector<string>();    }    int ii=s.length()-1;    for(;ii>=0;--ii)    {        string t=s.substr(ii,s.length()-ii);       if(wordDict.find(t)!=wordDict.end())        {            break;        }    }    if(ii<0)    {        return vector<string>();    }    for(int i=1;i<=s.length();++i)    {        string t=s.substr(0,i);        dp1[i]=vector<string>();        if(wordDict.find(t)!=wordDict.end())        {            dp1[i].push_back(t);        }         for(int j=1;j<i;++j)            {                if(dp1[j].size()>0)                {                    string t1=s.substr(j,i-j);                    if(wordDict.find(t1)!=wordDict.end())                   {                      for(int k=0;k<dp1[j].size();++k)                      {                        string t3=dp1[j][k];                        t3=t3+" "+t1;                        dp1[i].push_back(t3);                     }                   }                }             }        }    return dp1[s.length()];    }
0 0
原创粉丝点击