Given a dictionary of valid words and an input text, write a function to check if the input text can be decomposed into valid words from dictionary.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.
static string dic[4]={"bed","bath","beyond","and"};
bool decomps(string txt)
{
map<string,bool> dm;
for(int i=0;i<4;i++)
dm[dic[i]]=true;
vector<bool> t(txt.size()+1,false);
t[0]=true;
for(int k=1;k<=txt.size();k++)
{
bool candecomp=false;
for(int i=0;i<k;i++)
{
string srch=txt.substr(i,k-i);
map<string,bool>::iterator f=dm.find(srch);
if(t[i]==true && f!=dm.end())
{
t[k]=true;
break;
}
}
}
return t[txt.size()];
}
void test_decomp()
{
cout << decomps("bedbathandbeyond");
}
No comments :
Post a Comment