https://leetcode.com/problems/buddy-strings/description/
https://leetcode.com/problems/buddy-strings/discuss/141780/Easy-Understood
https://leetcode.com/problems/buddy-strings/discuss/141794/Java-O(1)-space-O(n)-time
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
If
A.length() != B.length()
: no possible swap
If
A == B
, we need swap two same characters. Check is duplicated char in A
.
In other cases, we find index for
A[i] != B[i]
. There should be only 2 diffs and it's our one swap. public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) return false;
if (A.equals(B)) {
Set<Character> s = new HashSet<Character>();
for (char c : A.toCharArray()) s.add(c);
return s.size() < A.length();
}
List<Integer> dif = new ArrayList<>();
for (int i = 0; i < A.length(); ++i) if (A.charAt(i) != B.charAt(i)) dif.add(i);
return dif.size() == 2 && A.charAt(dif.get(0)) == B.charAt(dif.get(1)) && A.charAt(dif.get(1)) == B.charAt(dif.get(0));
}
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length())
return false;
if (A.equals(B)) {
int[] count = new int[26];
for (int i = 0; i < A.length(); ++i)
count[A.charAt(i) - 'a']++;
for (int c : count)
if (c > 1)
return true;
return false;
} else {
int first = -1, second = -1;
for (int i = 0; i < A.length(); ++i) {
if (A.charAt(i) != B.charAt(i)) {
if (first == -1)
first = i;
else if (second == -1)
second = i;
else
return false;
}
}
return (second != -1 && A.charAt(first) == B.charAt(second) && A.charAt(second) == B.charAt(first));
}
}
https://leetcode.com/problems/buddy-strings/discuss/141794/Java-O(1)-space-O(n)-time
public boolean buddyStrings(String A, String B) {
if (A == null || B == null || A.length() != B.length()) return false;
int a = -1, b = -1, diff = 0;
int[] count = new int[26];
// check if able to switch with the same character.
boolean canSwitch = false;
for (int i = 0; i < A.length(); i++) {
if (++count[A.charAt(i) - 'a'] >= 2) canSwitch = true;
if (A.charAt(i) != B.charAt(i)) {
diff++;
if (a == -1) a = i;
else if (b == -1) b = i;
}
}
return (diff == 0 && canSwitch) || (diff == 2 && A.charAt(a) == B.charAt(b) && A.charAt(b) == B.charAt(a));
}