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
Example 2:
Input: A = “ab”, B = “ab”
Output: false
Example 3:
Input: A = “aa”, B = “aa”
Output: true
Example 4:
Input: A = “aaaaaaabc”, B = “aaaaaaacb”
Output: true
Example 5:
Input: A = “”, B = “aa”
Output: false
Note:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.
思路:
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.
代码:
class Solution {
public boolean buddyStrings(String A, String B) {
//Input: A = "", B = "aa" Output: false
if(A.length()!=B.length())
return false;
//Input: A = "ab", B = "ab" Output: false
//Input: A = "aa", B = "aa" Output: true
if(A.equals(B)){//去重复
Set<Character>set=new HashSet<>();
for(char c:A.toCharArray())
set.add(c);
return set.size()<A.length();
}
//Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
List<Integer> dif=new ArrayList<>();
for (int i = 0; i <A.length() ; i++) {
if(A.charAt(i)!=B.charAt(i))
dif.add(i);//记录下标,最多有2个元素
}
return dif.size()==2
&&A.charAt(dif.get(0))==B.charAt(dif.get(1))
&&A.charAt(dif.get(1))==B.charAt(dif.get(0));
}
}