给定两个长度相等的,由小写字母组成的字符串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;
}