给定两个由小写字母构成的字符串 A
和 B
,只要我们可以通过交换 A
中的两个字母得到与 B
相等的结果,就返回 true
;否则返回 false
。
示例 1:
输入: A = "ab", B = "ba" 输出: true
示例 2:
输入: A = "ab", B = "ab" 输出: false
示例 3:
输入: A = "aa", B = "aa" 输出: true
示例 4:
输入: A = "aaaaaaabc", B = "aaaaaaacb" 输出: true
示例 5:
输入: A = "", B = "aa" 输出: false
提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A
和B
仅由小写字母构成。
思路:
1. 两个字符串是亲密字符串的条件:
a.A字符串与B字符串相同,且A字符串的字符种类个数不能等于A字符串的长度。
b.A字符串与B字符串长度相同,且A与B中刚好有两个字符不同。
class Solution {
public boolean buddyStrings(String A, String B) {
if(A.length()==0||B.length()==0) {
return false;
}
if(A.length()!=B.length()) {
return false;
}
if(A.equals(B)) {
Set<Character> set=new HashSet<Character>();
for(int i=0;i<A.length();i++) {
set.add(A.charAt(i));
}
if(set.size()==A.length()) {
return false;
}
return true;
}
int count=0;
Set<Character> set1=new HashSet<Character>();
Set<Character> set2=new HashSet<Character>();
for(int i=0;i<A.length();i++) {
if(A.charAt(i)!=B.charAt(i)) {
set1.add(A.charAt(i));
set2.add(B.charAt(i));
count++;
}
if(count>2) {
return false;
}
}
if(count==2&&set1.equals(set2)) {
return true;
}
return false;
}
}