Buddy Strings
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
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
Constraints:
- 0 <= A.length <= 20000
- 0 <= B.length <= 20000
- A and B consist only of lowercase letters.
Solution:
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) {
return false;
}
int[] chars = new int[26];
boolean repeat = false;
Map<Character, Character> map = new HashMap();
for (int i = 0; i < A.length(); i ++) {
char a = A.charAt(i);
char b = B.charAt(i);
chars[a - 'a'] ++;
if (chars[a - 'a'] > 1) {
repeat = true;
}
if (a == b) {
continue;
}
if (map.size() >= 2) {
return false;
} else if (map.size() == 1) {
if (map.containsKey(b)) {
if (map.get(b) == a) {
map.put(a, b);
continue;
}
}
return false;
} else {
map.put(a, b);
}
}
return map.size() == 2 || (repeat && map.size() == 0);
}
}