0859. Buddy Strings (E)
Buddy Strings (E)
题目
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.
题意
判断一个字符串能否通过互换两个字母来变成另一个字符串。
思路
如果两个字符串相同,那么只要判断字符串中是否存在出现次数超过两次的字母;
如果不相同,那么判断是不是只有两个位置的字母不相同且将这两个字母互换后能使字符串相同。
代码实现
Java
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length() || A.length() < 2) {
return false;
}
if (A.equals(B)) {
int[] count = new int[26];
for (char c : A.toCharArray()) {
if (count[c - 'a'] > 0) {
return true;
}
count[c - 'a']++;
}
return false;
} else {
List<Integer> diff = new ArrayList<>();
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(i)) {
diff.add(i);
if (diff.size() > 2) {
return false;
}
}
}
return diff.size() == 2 && A.charAt(diff.get(0)) == B.charAt(diff.get(1))
&& A.charAt(diff.get(1)) == B.charAt(diff.get(0));
}
}
}