LeetCode#859: Buddy Strings
阿新 • • 發佈:2018-11-17
Description
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
Input: A = "ab", B = "ba"
Output: true
Input: A = "ab", B = "ab"
Output: false
Input: A = "aa", B = "aa"
Output: true
Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
Input: A = "", B = "aa"
Output: false
Note
- 0 <= A.length <= 20000
- 0 <= B.length <= 20000
- A and B consist only of lowercase letters.
Solution
這道題容易忽視兩個測試用例String A = "aa"; String B = "aa"
和String A = "abab"; String B = "abab"
,這兩類情況都應該返回true
,發現了這點其實比較好通過。
此題大致分為三種情況:
1、A與B長度不等,這時候肯定返回false。
2、A與B完全相同,則檢視字串中是否有重複的字母,有的話就返回true,因為交換重複的字母不會改變字串,且滿足了題目要求。否則,返回false。
3、A中有且僅有兩個字母與B不同,且交換之後就與B相同了,這時候返回true。否則,返回false。
class Solution {
public boolean buddyStrings(String A, String B) {
if(A.length() != B.length())
return false;
HashSet<Character> set = new HashSet<>();
char[] diffA = new char[2];
char[] diffB = new char[2];
int index = 0;
for (int i = 0; i < A.length(); i++) {
set.add(A.charAt(i));
if(A.charAt(i) != B.charAt(i)){
if(index == 2) return false;
diffA[index] = A.charAt(i);
diffB[index] = B.charAt(i);
index++;
}
}
if(index == 2) {
return (diffA[0] != 0 && diffA[1] != 0 && diffA[0] == diffB[1] && diffB[0] == diffA[1]);
} else if(index == 1) {
return false;
} else {
return (A.equals(B) && set.size() < A.length());
}
}
}