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 <= 200000 <= B.length <= 20000AandBconsist 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));
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/169297.html
標籤:其他
