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:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.

难度: Medium

题目:给定两字符串A和B且由小写字线组成,返回AB是否由仅交换两个字符可以相互生成。

思路:判断长度,记录不同位置的个数,记录是否有相同的字符。

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;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018393865
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞