【LeetCode】Word Break II

來源:互聯網
上載者:User

標籤:style   blog   http   color   width   strong   

Word Break II

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

 

我將解分為三步:

(1)構造如所示的兩級向量(vector<vector<int> > v)

 

向量v解釋:

‘t2‘及‘s3‘有成員-1,意為從-1+1個字元(‘c‘)到當前字元存在詞("cat"/"cats")。

‘d6‘有成員2和3,意為從第2+1個字元(‘s‘)和第3+1個字元(‘a‘)到當前字元存在詞("sand"/"and")並且存在從字串頭到當前字元的切分路徑。

‘g9‘有成員6,意為從第6+1個字元(‘d‘)到當前字元存在詞("dog")並且存在從字串開頭到當前字元的切分路徑。

(2)基於向量v逆向尋找詞,藉助棧

(3)詞以空格隔開,存入result向量

class Solution{public:    vector<string> result;    void printStack(stack<string> stk)    {        string output = "";        while(!stk.empty())        {            if(output == "")                output += stk.top();            else                output = output + " " + stk.top();            stk.pop();        }        result.push_back(output);    }    void check(vector<vector<int> > &v, int t, stack<string> stk, string s)    {        if(t == -1)        {            printStack(stk);            return ;        }        else        {            for(vector<string>::size_type st = 0; st < v[t].size(); st ++)            {                stk.push(s.substr(v[t][st]+1, t-v[t][st]));                check(v, v[t][st], stk, s);                stk.pop();            }        }    }    vector<vector<int> > buildv(string s, unordered_set<string> &dict)    {        vector<vector<int> > v(s.length());        for(string::size_type st1 = 0; st1 < s.length(); st1 ++)        {            for(string::size_type st2 = 0; st2 <= st1; st2 ++)            {                if(dict.find(s.substr(st2, st1-st2+1)) != dict.end())                {                    if(st2 == 0)                        v[st1].push_back(-1);                    else if(!v[st2-1].empty())                        v[st1].push_back(st2-1);                }            }        }        return v;    }    vector<string> wordBreak(string s, unordered_set<string> &dict)     {        vector<vector<int> > v = buildv(s, dict);        stack<string> stk;        check(v, v.size()-1, stk, s);        return result;    }};

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.