10. Buddy Strings

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

這題目不難,但要仔細分析所有狀況

- If the lengths differ, return False. - If the strings are the same with duplicate characters, return True. - Count the number of different characters. If the count is not 2, return False. - If the characters are equal to each other swapped, then return True. <-- 可以正確被swap

def buddyStrings(self, A, B):
  if len(A) != len(B): return False
  # abcc = abcc
  if A == B and len(A) > len(set(A)): return True

  diffa = []
  diffb = []
  for i in range(len(A)):
    if len(diffa) > 2:
      return False
    if A[i] != B[i]:
      diffa.add(A[i])
      diffb.add(B[i])

  if len(diffa) != 2:
    return False
  if diffa[0] == diffb[1] and diffa[1] == diffb[0]:
    return True

  return False

Last updated

Was this helpful?