[LeetCode] 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两字符串,问B中交换两个字母是否能变成A(必须交换)

判断可能产生的各种情况就行了,A,B两字符串长度不同,这么换肯定不可能相同

AB两字符串不同字母的个数,0,1,2,>2;

1,>2的情况就不用判了,肯定false;

0的情况判断是否有重复字母,2的时候比较那两个字母就行了

class Solution {
    public boolean buddyStrings(String A, String B) {
        if (A.length() != B.length())
            return false;
        List list = new ArrayList<>();
        HashSet set = new HashSet<>();
        boolean flag = false;
        for (int i = 0; i < A.length(); i++) {
            if (A.charAt(i) != B.charAt(i))
                list.add(i);
            if (!flag) {
                if (set.contains(A.charAt(i))) 
                    flag = true;
                else 
                    set.add(A.charAt(i));
            }
        }
        if (list.size() > 2 || list.size() == 1)
            return false;
        if (list.size() == 0) {
            if (flag)
                return true;
            else
                return false;
        }
        
        int i = list.get(0);
        int j = list.get(1);
        if (A.charAt(i) == B.charAt(j) && A.charAt(j) == B.charAt(i))
            return true;
        return false;
    }
}

 

转载于:https://www.cnblogs.com/Moriarty-cx/p/9751073.html

你可能感兴趣的:([LeetCode] 859. Buddy Strings)