我想实现将给定字符串分解为其组成字典单词问题的解决方案,但是我的代码给出了错误的输出,如“icecreamicecream”在输出中得到一些单词两次。请让我知道我出错的地方。以下是我的代码:给出错误的输出:如何将字符串分解为字典单词
#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;
}
对于字符串icecreamicecream:我想这是输出的顺序:我发现以线性方式的所有单词 我冰淇淋我冰淇淋冰淇淋冰淇淋 1,然后回溯得到剩余的话。
你的问题有几种解决方案,但你似乎并没有将它们分开(例如解决方案:'冰淇淋cream','冰淇淋icecream','我膏icecream' ... )。 – Synxis
根据我的输出显示应该是: 我冰淇淋我冰淇淋冰淇淋冰淇淋 – amiageek
你应该发布你期望/想要的问题(比你的评论更多的细节)。 – Synxis