Given two stringsA
andB
of lowercase letters, returntrue
if and only if we can swap two letters inA
so that the result equalsB
.
Example 1:
Input:
A =
"ab"
, B =
"ba"
Output:
true
Example 2:
Input:
A =
"ab"
, B =
"ab"
Output:
false
Example 3:
Input:
A =
"aa"
, B =
"aa"
Output:
true
Example 4:
Input:
A =
"aaaaaaabc"
, B =
"aaaaaaacb"
Output:
true
Example 5:
Input:
A =
""
, B =
"aa"
Output:
false
Note:
0
<
= A.length
<
= 20000
0
<
= B.length
<
= 20000
A
and
B
consist only of lowercase letters.class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) return false;
if (A.equals(B)){
Set<Character> set = new HashSet<>();
for (char c : A.toCharArray()){
set.add(c);
}
return set.size() < A.length();
}
List<Integer> diff = new ArrayList<>();
for (int i = 0; i < A.length(); i++){
if (A.charAt(i) != B.charAt(i)) diff.add(i);
}
return diff.size() == 2 && A.charAt(diff.get(0)) == B.charAt(diff.get(1)) && A.charAt(diff.get(1)) == B.charAt(diff.get(0));
}
}