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.less

Example 1:code

Input: A = "ab", B = "ba"
Output: true

Example 2:字符串

Input: A = "ab", B = "ab"
Output: false

Example 3:string

Input: A = "aa", B = "aa"
Output: true

Example 4:it

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:io

Input: A = "", B = "aa"
Output: false

Note:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.table

難度: Mediumast

題目:給定兩字符串A和B且由小寫字線組成,返回AB是否由僅交換兩個字符能夠相互生成。class

思路:判斷長度,記錄不一樣位置的個數,記錄是否有相同的字符。im

Runtime: 3 ms, faster than 81.94% of Java online submissions for Buddy Strings.
Memory Usage: 38.6 MB, less than 50.00% of Java online submissions for Buddy Strings.

class Solution {
    public boolean buddyStrings(String A, String B) {
        if (A.length() != B.length()) {
            return false;
        }
        
        int[] tableA = new int[26];
        int[] tableB = new int[26];
        int diffPosition = 0;
        for (int i = 0; i < A.length(); i++) {
            char a = A.charAt(i);
            char b = B.charAt(i);
            if (a != b) {
                diffPosition++;
            }
            if (diffPosition > 2) {
                return false;
            }
            tableA[a - 'a']++;
            tableB[b - 'a']++;
        }
        
        boolean duplicated = false;
        for (int i = 0; !duplicated && i < 26; i++) {
            if (tableA[i] != tableB[i]) {
                return false;
            }
            duplicated = tableA[i] > 1 ? !duplicated : duplicated;
        }
        
        return 2 == diffPosition || duplicated;
    }
}
相關文章
相關標籤/搜索