Given two strings
true if you can swap two letters in
a so the result is equal to
b, otherwise, return
Swapping letters is defined as taking two indices
j (0-indexed) such that
i != j and swapping the characters at
- For example, swapping at indices
Input: a = "ab", b = "ba" Output: true Explanation: You can swap a = 'a' and a = 'b' to get "ba", which is equal to b.
Input: a = "ab", b = "ab" Output: false Explanation: The only letters you can swap are a = 'a' and a = 'b', which results in "ba" != b.
Input: a = "aa", b = "aa" Output: true Explanation: You can swap a = 'a' and a = 'a' to get "aa", which is equal to b.
Input: a = "aaaaaaabc", b = "aaaaaaacb" Output: true
1 <= a.length, b.length <= 2 * 104
bconsist of lowercase letters.
Solution in Python
class Solution: def buddyStrings(self, a: str, b: str) -> bool: diff = [(i,j) for i,j in zip(a,b) if i!=j] freq = Counter(a) if len(a) != len(b): return False if len(diff) == 2 and diff == diff and diff==diff: return True elif len(diff) == 0 and any(map(lambda x: x>1, freq.values())): return True else: return False