s = abcd
t = acbd
则s和t完美匹配
1,遍历s和t中每个字符 分别用count 和index记录不相同字符的数量和最后一个不相同字符的下标
如果两个字符串完美匹配 则count的值一定为2 ,此时index的下标记录的是不相同字符对最右边那个位置
判断一下 s中右边字符是否等于t左边字符 且 t右边字符等于s中左边字符
只需要分别讨论count的值就可以了
count == 0 完全相同 匹配
count == 1 只有一个位置不同 无论如何交换也不会完美匹配
count > 2 因为至多交换一次相邻位置的字符对 所以不会完美匹配
#include<iostream>
#include<string>
using namespace std;
const int N = 10010;
string s,t;
int main()
{
cin >> s >> t;
int diff_count = 0,diff_index = -1;
//遍历s 和 t 字符串
for(int i = 0; i < s.size(); i ++)
if(s[i] != t[i])
{
diff_count ++,diff_index = i;
}
//完全相同
if(diff_count == 0) puts("Yes");
//完美匹配最多只有两个不同的数量
else if(diff_count > 2) puts("no");
else if(diff_count == 1) puts("no");// 只有一个位置不一样 怎么交换也不会完美匹配
else if(diff_count == 2)
{
if(s[diff_index] == t[diff_index - 1] && s[diff_index - 1] == t[diff_index]) puts("Yes");
else puts("no");
}
return 0;
}