题解 CF186A 【Comparing Strings】
就用 STL 排序一下,然后找不一样的地方有几个。
这里我用的是稳定排序 stable_sort,实测比 sort 快一点。
我没有和大家一样比长度,因为如果长度不一样那 sort 完两个能一样吗?
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
int len = min(a.length(), b.length()), dif = 0; // 从最小的长度来
for (register int i = 0; i <= len; i++)
{
if (a[i] != b[i]) dif++; // 不一样,累加
}
stable_sort(a.begin(), a.end()); // 和sort一样
stable_sort(b.begin(), b.end());
cout << (a == b && dif <= 2 ? "YES" : "NO") << endl;
//system("pause");
return 0;
}

浙公网安备 33010602011771号