Leetcode 889 Solution

This article provides solution to leetcode question 889 (buddy-strings)

https://leetcode.com/problems/buddy-strings

Solution

class Solution(object): def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ if len(A) != len(B): return False
cnt = collections.defaultdict(int)
s1 = set() s2 = set() for ch1, ch2 in zip(A, B): if ch1 != ch2: s1.add(ch1) s2.add(ch2) cnt[ch1] += 1
if len(s1) == 0: return True if [v for v in cnt.values() if v > 1] else False elif len(s1) == 2: return s1 == s2 else: return False