Word Break Problem

Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null.

For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].

Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].

Example:

Input:  dict = {"quick", "brown", "the", "fox"}, str = "thequickbrownfox"
Output: [the, quick, brown, fox]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void wordBreakString(vector<string&dict,
                     string strvector<string&res)
{

    if (str.size() == 0)
    {
        return;
    }

    for (int i = 1i <= str.size(); i++)
    {

        string prefix = str.substr(0i);

        if (find(dict.begin(), dict.end(), prefix!= dict.end())
        {
            res.push_back(prefix);
            wordBreakString(dictstr.substr(i), res);
        }
    }
}

int main()
{

    vector<stringdict = {"quick""brown""the""fox"};

    string str = "thequickbrownfox";

    vector<stringres;
    wordBreakString(dictstrres);

    cout<<"[";
    for(int i=0;i<res.size();i++)
     {
         cout<<res[i];
         if(i!=res.size()-1)
           cout<<", ";
     }
     cout<<"]";
    return 0;
}


No comments:

Post a Comment