Press "Enter" to skip to content

Buddy Strings-LeetCode#859

859. Buddy Strings

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:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.

思路:给定两个字母A和B的小写字母,当且仅当我们可以在A中交换两个字母以使结果等于B时返回true。三个条件:

  1. A.length() != B.length(): 长度不同 false
  2. A == B, 如果两个值相同,必需要存在重复的字符
  3. 其他情况 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;
            }
        }

    }
}

 

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注