题目:
解答:
只有两种情况下会返回True
1、有两个不一样的字母,交换位置后两个字母相等
2、所有字母都一样,则必须存在重复的字母
1 class Solution { 2 public: 3 bool buddyStrings(string A, string B) 4 { 5 if(A.length() != B.length()) 6 return false; 7 8 map<char,int> a; 9 int i=0; 10 int j=A.length()-1; 11 12 // 处理AB相等的情况 13 if(A==B) 14 { 15 //只要有某个字符出现两次就够了 16 for(int i=0;i<A.length();i++) 17 { 18 char tt=A[i]; 19 a[tt]++; 20 if(a[tt]>1) 21 { 22 return true; 23 } 24 } 25 return false; 26 } 27 //处理AB不等的情况 28 else 29 { 30 while(i<j) 31 { 32 if(A[i]==B[i]) 33 i++; 34 else if(A[j]==B[j]) 35 j--; 36 else 37 break; 38 } 39 if(i==j) 40 return false; 41 else 42 { 43 char temp=A[i]; 44 A[i]=A[j]; 45 A[j]=temp; 46 } 47 if(A==B) 48 return true; 49 else 50 return false; 51 } 52 } 53 };
原文:https://www.cnblogs.com/ocpc/p/12823579.html