[LeetCode]#859. Buddy Strings

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.

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 Trueif 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

--

--

More from Fatboy Slim

Interesting in any computer science.