题目
给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
交换字母的定义是取两个下标 i 和 j (下标从 0 开始),只要 i!=j 就交换 A[i] 和 A[j] 处的字符。例如,在 “abcd” 中交换下标 0 和下标 2 的元素可以生成 “cbad” 。
示例 1:
输入: A = “ab”, B = “ba”
输出: true
解释: 你可以交换 A[0] = ‘a’ 和 A[1] = ‘b’ 生成 “ba”,此时 A 和 B 相等。
示例 2:
输入: A = “ab”, B = “ab”
输出: false
解释: 你只能交换 A[0] = ‘a’ 和 A[1] = ‘b’ 生成 “ba”,此时 A 和 B 不相等。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/buddy-strings
class Solution {
public boolean buddyStrings(String A, String B) {
if(A==null||B==null||A.length()<2||B.length()<2)
return false;
char[] a = A.toCharArray();
char[] b = B.toCharArray();
if(A.equals(B)){
if(a.length>26)
return true;
Set<Character> set = new HashSet<>();
for(int i=0;i<a.length;i++){
set.add(a[i]);
}
if(set.size()==a.length)
return false;
return true;
}
if(a.length!=b.length)
return false;
int count = 0;
for(int i=0;i<a.length;i++){
if(a[i]!=b[i]&&count==0){
a[0] = a[i];
b[0] = b[i];
++count;
}
else if(a[i]!=b[i]){
a[1] = a[i];
b[1] = b[i];
++count;
}
if(count>3)
return false;
}
if(a[0]==b[1]&&a[1]==b[0])
return true;
else
return false;
}
}