【发布时间】:2019-08-07 19:33:50
【问题描述】:
问题
我首先将一个字符串分成不同的单词,然后检查是否存在反向单词。我为每个单词制作一个不同的字符串,然后将其反转,然后将其与其他字符串进行比较。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout<<"the string inputted is "<<str;
char ch=str[0];
int i=0;
int sp_count=0;
while(ch!='\0')
{
ch=str[i];
if(ch==' ')
{
sp_count++;
}
i++;
}
string words[sp_count+1];
ch=str[0];
i=0;
int w=0,it=0;
while(ch!='\0')
{
ch=str[i];
if(ch==' ')
{
w++;
i++;
continue;
}
words[w]=words[w]+ch;
i++;
}
for(int i=0;i<sp_count+1;i++)
{
cout<<words[i]<<endl;
}
for(int i=0;i<sp_count+1;i++)
{ string temp=words[i];
reverse(temp.begin(),temp.end());
for(int j=i+1;j<sp_count+1;j++)
{ int x=10;
x=temp.compare(words[j]);
if(x==0)
{
cout<<"strings "<<temp << " and "<<words[j]<<" are equal"<<endl;
}
else
{
cout<<"strings "<<temp << " and "<<words[j]<<" are not equal"<<endl;
}
}
}
return 0;
}
当我输入字符串时:
Hello is si
输出是:
strings olleh and is are not equal
strings olleh and si are not equal
strings si and si are not equal
代码没有返回正确的输出。
【问题讨论】:
-
这按预期工作:ideone.com/9mqB5e 由于您的问题不包含minimal reproducible example 我无法测试您的代码,我只能告诉您它一定有问题。也许您应该使用调试器或打印更多数据。
-
另外,您的复杂度是 O(N^2),非常糟糕。考虑使用不同的数据结构(如果您有超过 10 个元素)。也许使用
std::set<std::string>(总 O(N log N) 和一个好的常数,std::unordered_set<std::string>(总 O(N) 和一个非常差的常数),或者甚至在一个排序的字符串列表中使用二进制搜索(总 O(N log N) 具有非常好的常数) -
能否给出完整的代码。当我设置
words = {"hello", "is", "si"}和sp_count = words.size() - 1时,一切都按预期工作。 -
在您打印单词的循环中,将
cout<<words[i]<<endl;更改为cout << "'" << words[i] << "'" << endl;,您将看到问题所在。在您打印字符串不相等的输出中也应该很明显。考虑寻找更好的分割字符串的方法,或者如何逐字接受输入。
标签: c++ arrays string function loops