如何比较这两个字符串是否相等?

两个字符串相等的条件如下,字符串中的每个字母出现的次数都相等。例如: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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值