[LeetCode]#859. Buddy Strings

Fatboy Slim
2 min readMar 22, 2020

Environment: Python 3.7

Key technique: set, .append

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

Analysis:

This problem need follow below rule.

  1. str A length = Str B length
  2. str A or B can’t be None.
  3. string A and B can be the same as “aa” and “aa”, but can’t be this “ab” and “ab”. We need swap two letter.
  4. The different letter can’t larger than 2, we need check two str can be the same when we swap them.

Solution:

class Solution(object):
def buddyStrings(self, A, B):
if len(A) != len(B):
return False
list_a = list(A)
list_b = list(B)
a_diff = []
b_diff = []
for i in range(len(list_a)):
if list_a[i] != list_b[i]:
a_diff.append(list_a[i])
b_diff.append(list_b[i])
if len(a_diff) > 2:
return False
if len(a_diff) == 2 and a_diff[::-1] == b_diff:
return True
if len(a_diff) == 0:
if len(list_a) > len(set(list_a)):
return True
return False

Submitted result:

Lesson learn:

Function set can take out each letter from list and it is very useful. If A is ”ab” and set(A) is {‘a’, ‘b’}.

Reference:

https://leetcode.com/problems/buddy-strings/discuss/513334/python-simple-and-easy

--

--