两个字符串相等的条件如下,字符串中的每个字母出现的次数都相等。例如:abbcd 和acdbb是相等的,因为a都出现1次,b都出现2次,c都出现3次,d都出现4次。
解题思路:
可以使用一个额外的数组,将第二个字符串赋给额外的数组,然后遍历第一个数组和额外的数组,找到相同的字符,则将额外数组中相同的字符赋值为空格。直到额外的数组中字符串全部为空为止。
代码如下:
#include<iostream>
using namespace std;
int main()
{
char *str1=(char*)malloc(sizeof(char));
char *str2=(char*)malloc(sizeof(char));
char *str3;
char ch;
int count=1;
int i,j;
while ((ch=getchar())!='\n')
{
count++;
str1=(char*)realloc(str1,sizeof(char)*(count));
str1[count-2]=ch;
}
str1[count-1]='\0';
count=1;
while ((ch=getchar())!='\n')
{
count++;
str2=(char*)realloc(str2,sizeof(char)*(count));
str2[count-2]=ch;
}
str2[count-1]='\0';
str3=(char*)malloc(sizeof(char)*count);
count=0;
while (str2[count]!='\0')
{
str3[count]=str2[count];
count++;
}
str3[count]='\0';
for (i=0;i<strlen(str1);i++)
{
for (j=0;j<strlen(str3);j++)
{
if (str1[i]==str3[j])
{
str3[j]=' ';
}
}
}
count=0;
for (j=0;j<strlen(str3);j++)
{
if (str3[j]==' ')
{
count++;
}
}
if ((count==strlen(str1))&&(count==strlen(str3)))
{
cout<<"相等"<<endl;
}
else
{
cout<<"不相等"<<endl;
}
free(str1);
free(str2);
free(str3);
return 0;
}