I am trying to implement the solution of breaking a given string into its constituent dictionary words problem, but my code is giving wrong output for strings like "icecreamicecream" wherein I am getting some words twice in the output. Please let me know where I am going wrong. Following is my code:
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include<string.h>
#define MAX 12
using namespace std;
string arr[]={"i", "like", "sam", "sung", "samsung", "mobile", "ice","cream", "icecream", "man", "go", "mango"};
set<string> dictionary (arr,arr+MAX);
int cnt=0;
void print_words(string str,int i,int j)//i and j denote starting and ending indices respectively of the string to be matched
{
if(i>j||j>=str.length()||i>=str.length())
{
return;
}
string temp (str, i, j-i+1);
if(dictionary.find(temp)==dictionary.end())
print_words(str,i,j+1);
else
{
cout<<temp<<endl;
cnt++;
print_words(str,j+1,j+1);
print_words(str,i,j+1);
}
}
int main()
{
string str;
cin>>str;
print_words(str,0,0);
cout<<cnt<<endl;
return 0;
}
For the string icecreamicecream: I want this to be the order of the output: i ice cream i ice cream icecream icecream 1st i am finding all words in linear fashion, then backtracking to get the remaining words.