C++每日一题——字符串距离计算

给定两个长度相等的,由小写字母组成的字符串S1和S2,定义S1和S2的距离为两个字符串有多少个位置上的字母不相等。
现在可以选定两个字母X1和X2,将S1中的所有字母X1均替换成X2。(X1和X2可以相同)
希望知道执行一次替换之后,两个字符串的距离最少为多少。字符串的最大长度为50000
例如输入:
“aabb” “ccdd” 将第一个字符串的a替换为c,则第一个字符串为“ccbb”,距离为2
若不替换字符,则距离为4

#include<iostream>
#include <string>
using namespace std;
const int LEN = 50000;
const char SPACE = '\0';
long calDistance(string &str1, string &str2)
{
	if (str1.size() != str2.size())
	{
		cout << "the input string's length is not equal." << endl;
		return -1;
	}
	if (str1.size() > LEN)
	{
		cout << "the input string's length is too long." << endl;
		return -1;
	}
	long distance = 0;
	for (long i = 0; i < str1.size(); ++i)
	{
		if (str1[i] == str2[i])
		{
			distance++;
		}
	}
	return distance;
}

void changeString(string &str, string &oldchr, string &newchr)
{
	if (newchr[0] == SPACE || oldchr[0] == SPACE)
	{
		cout << "Don't need to change the input string." << endl;
		return;
	}
	while (str.find_first_of(oldchr) != -1)
	{
		str.replace(str.find(oldchr),1, newchr);
	}
	cout << "the string is " << str << endl;
	return;
}

int main()
{
	string str1("");
	string str2("");
	string oldchr("");
	string newchr("");
	cout << "Please input str1:" << endl;
	getline(cin, str1);
	cout << "Please input str2:" << endl;
	getline(cin, str2);
	cout << "Please input oldchr:" << endl;
	getline(cin, oldchr);
	cout << "Please input newchr:" << endl;
	getline(cin, newchr);
	changeString(str1, oldchr, newchr);
	long distance = 0;
	distance = calDistance(str1, str2);
	cout <<"the distance is "<< distance << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bussy-Lake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值