zoukankan      html  css  js  c++  java
  • word-break-ii leetcode C++

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

    C++

    class Solution {
    public:
        vector<string> wordBreak(string s, unordered_set<string> &dict){
            vector<string> result;
            if(dict.find(s)!=dict.end()) 
                result.push_back(s);
            for(int i=1;i<s.size();i++) {
                string w = s.substr(i);
                if(dict.find(w) == dict.end())
                    continue;
                string str = s.substr(0,i);
                vector<string> left = wordBreak(str,dict);
                Add(left,w);
                result.insert(result.begin(), left.begin(), left.end());
            }         
            return result;
        }
        
        void Add(vector<string> &str, string w){
            for(vector<string>::iterator it=str.begin();it!=str.end();it++)
                *it += " " + w;     
        }
        
        vector<string> wordBreak2(string s, unordered_set<string> &dict){
            vector<string> result;
            if (dict.find(s) != dict.end()) 
                result.push_back(s);
            for(int i = s.size() -1; i > 0;i--){
                string w = s.substr(i);
                if(dict.find(w) == dict.end())
                    continue;
                string str = s.substr(0,i);
                vector<string> left = wordBreak(str,dict);
                Add(left,w);
                result.insert(result.end(),left.begin(),left.end());
            }
            return result;
        }
    };
  • 相关阅读:
    day 48
    40 协程 多路复用
    JQuery
    JS DOMBOM
    psotgres、timescaledb
    crontab命令
    Go语言结构体和方法
    Go语言锁的使用
    Go语言map数据结构
    ZOJ 3777 Problem Arrangement
  • 原文地址:https://www.cnblogs.com/vercont/p/10210240.html
Copyright © 2011-2022 走看看