题目

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:

  1. Input: A = "ab", B = "ba"
  2. Output: true
  3. Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.

Example 2:

  1. Input: A = "ab", B = "ab"
  2. Output: false
  3. Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.

Example 3:

  1. Input: A = "aa", B = "aa"
  2. Output: true
  3. Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.

Example 4:

  1. Input: A = "aaaaaaabc", B = "aaaaaaacb"
  2. Output: true

Example 5:

  1. Input: A = "", B = "aa"
  2. Output: false

Constraints:

  • 0 <= A.length <= 20000
  • 0 <= B.length <= 20000
  • A and B consist of lowercase letters.

题意

判断一个字符串能否通过互换两个字母来变成另一个字符串。

思路

如果两个字符串相同,那么只要判断字符串中是否存在出现次数超过两次的字母;

如果不相同,那么判断是不是只有两个位置的字母不相同且将这两个字母互换后能使字符串相同。


代码实现

Java

  1. class Solution {
  2. public boolean buddyStrings(String A, String B) {
  3. if (A.length() != B.length() || A.length() < 2) {
  4. return false;
  5. }
  6. if (A.equals(B)) {
  7. int[] count = new int[26];
  8. for (char c : A.toCharArray()) {
  9. if (count[c - 'a'] > 0) {
  10. return true;
  11. }
  12. count[c - 'a']++;
  13. }
  14. return false;
  15. } else {
  16. List<Integer> diff = new ArrayList<>();
  17. for (int i = 0; i < A.length(); i++) {
  18. if (A.charAt(i) != B.charAt(i)) {
  19. diff.add(i);
  20. if (diff.size() > 2) {
  21. return false;
  22. }
  23. }
  24. }
  25. return diff.size() == 2 && A.charAt(diff.get(0)) == B.charAt(diff.get(1))
  26. && A.charAt(diff.get(1)) == B.charAt(diff.get(0));
  27. }
  28. }
  29. }