Skip to content

Latest commit

 

History

History
57 lines (49 loc) · 1.35 KB

File metadata and controls

57 lines (49 loc) · 1.35 KB

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.

Solutions (Python)

1. Solution

class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        if len(A) != len(B):
            return False
        if A == B and len(set(A)) != len(A):
            return True
        a, b = '', ''
        for k, v in enumerate(A):
            if v != B[k]:
                a += v
                b += B[k]
            if len(a) > 2:
                return False
        return len(a) == 2 and a == b[::-1]