头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):859. Buddy Strings》

 2月前  •   LeetCode  •     •   12  •   0

Question:

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

Solution:

JAVAclass Solution {
    public boolean buddyStrings(String A, String B) {
        if(A.equals(B)){
            int[] map = new int[26];
            for(char c: A.toCharArray()) map[c - 'a']++;
            
            for(int count: map){
                if(count >=2) return true;
            }
            return false;
        }else{
            // A can swap to B, A[i] == B[j] && A[j] == B[i]
            int ch1 = -1, ch2 = -1;
            for(int i=0; i<A.length(); i++){
                if(A.charAt(i) != B.charAt(i)){
                    if(ch1 == -1) ch1 = i;
                    else if(ch2 == -1) ch2 = i;
                    else return false;
                }
            }
            return ch2 != -1 && A.charAt(ch1) == B.charAt(ch2) && A.charAt(ch2) == B.charAt(ch1);
    }
    }
}

 

上一篇:
下一篇:

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!