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.

Two cases:

  1. Exactly two chars are different, and two strings are same with these chars swapped
  2. Two strings are exactly same, the string has duplicate char, so we can pretend to have a swap.

 

class Solution {

    /**
     * @param String $A
     * @param String $B
     * @return Boolean
     */
    function buddyStrings($A, $B) {
        if(empty($A) || empty($B) || count($A) !== count($B)){
            return false;
        }
        
        if($A == $B){
            if(strlen(count_chars($A, 3)) != strlen($A)){
                // Check is there're duplicate chars
                return true;
            }
        }
        
        $diff_a = [];
        $diff_b = [];
        
        
        for($i = 0; $i < strlen($A); $i ++){
            if($A[$i] !== $B[$i]){
                $diff_a[] = $A[$i];
                $diff_b[] = $B[$i];
            }
        }

        return  count($diff_b) == 2
            && $diff_a[1] == $diff_b[0] 
            && $diff_a[0] == $diff_b[1]; 
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.