2020-10-12
859. Buddy Strings
Question:
Given two strings A
and B
of lowercase letters, return true
if you can swap two letters in A
so the result is equal to B
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at A[i]
and A[j]
. For example, swapping at indices 0
and 2
in "abcd"
results in "cbad"
.
Example 1:
Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
Example 2:
Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
Example 3:
Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.
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
andB
consist of lowercase letters.
Solution:
Find if two strings are the same first; if true, look for the duplicate character. Otherwise, check how many characters are different.
class Solution {
public boolean buddyStrings(String A, String B) {
if (A == null || B == null || A.length() != B.length()){
return false;
}
int pointer_a = -1;
int pointer_b = -1;
int diff = 0;
int[] counter = new int[26];
if (A.equals(B)) {
for (char c : A.toCharArray()) {
if (++counter[c - 'a'] >= 2) {
return true;
}
}
}
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
if (pointer_a == -1) {
pointer_a = i;
} else if (pointer_b == -1) {
pointer_b = i;
}
diff++;
}
}
return (diff == 2 && A.charAt(pointer_a) == B.charAt(pointer_b) && A.charAt(pointer_b) == B.charAt(pointer_a));
}
}
It can also do in a single pass.
class Solution {
public boolean buddyStrings(String A, String B) {
int pointer_a = -1;
int pointer_b = -1;
if (A == null || B == null || A.length() != B.length()){
return false;
}
int diff = 0;
boolean duplicate = false;
int[] counter = new int[26];
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
if (pointer_a == -1) {
pointer_a = i;
} else if (pointer_b == -1) {
pointer_b = i;
}
diff++;
} else {
counter[A.charAt(i) - 'a']++;
if (counter[A.charAt(i) - 'a'] >= 2) {
duplicate = true;
}
}
}
return (diff == 0 && duplicate) || (diff == 2 && A.charAt(pointer_a) == B.charAt(pointer_b) && A.charAt(pointer_b) == B.charAt(pointer_a));
}
}