原文地址:https://www.jianshu.com/p/3ec6e0995562

时间限制:1秒 空间限制:32768K

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

我的代码

word-break-ii

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> res;
        if(dict.find(s)!=dict.end())
            res.push_back(s);
        int siz=s.size();
        for(int i=1;i<siz;i++){
            string word=s.substr(i);//截取至末尾
            if(dict.find(word)==dict.end())
                continue;
            vector<string> tmpRes=wordBreak(s.substr(0,i),dict);
            combine(tmpRes,word);
            res.insert(res.begin(),tmpRes.begin(),tmpRes.end());
        }
        return res;
    }
    void combine(vector<string> &inp, const string &word){
        int siz=inp.size();
        for(int i=0;i<siz;i++)
            inp[i]+=(" "+word);
    }
};

运行时间:7ms
占用内存:608k

相关文章:

  • 2021-12-17
  • 2021-08-21
  • 2021-06-06
  • 2022-01-19
  • 2021-10-24
  • 2021-06-12
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-20
  • 2021-09-24
  • 2021-09-03
  • 2021-09-27
相关资源
相似解决方案