859. Buddy Strings
Given two strings
Example 1:
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
andB
consist only of lowercase letters.
思路:给定两个字母A和B的小写字母,当且仅当我们可以在A中交换两个字母以使结果等于B时返回true。三个条件:
A.length() != B.length()
: 长度不同 falseA == B
, 如果两个值相同,必需要存在重复的字符- 其他情况
A[i] != B[i]
只会出现两次
代码如下:
public class BuddyStrings { public boolean buddyStrings(String A, String B) { if (A.length() != B.length()) return false; if (A.equals(B)) { Set<Character> set = new HashSet<>(); for (char c : A.toCharArray()) { set.add(c); } if (set.size() == A.length()) { return false; } else { return true; } } else { StringBuilder stringBuilderA = new StringBuilder(); StringBuilder stringBuilderB = new StringBuilder(); for (int i = 0; i < A.length(); i++) { if (A.toCharArray()[i] != B.toCharArray()[i]){ stringBuilderA.append(A.toCharArray()[i]); stringBuilderB.append(B.toCharArray()[i]); } } if (stringBuilderA.toString().equals(stringBuilderB.reverse().toString())){ return true; }else { return false; } } } }