Title: Buddy Strings Source: leetcode.com
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 = “aaabcccd”, B = “aaadcccb”
Output: true
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
''' https://leetcode.com/problems/buddy-strings/ ''' class Solution(object): def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ lnA, lnB = len(A), len(B) if (lnA != lnB) or lnA < 2: return False dif = [ord(a) - ord(b) for a,b in zip(A, B) if ord(a) - ord(b) != 0] if len(dif) == 0: d = {} for char in A: if char in d: return True else: d[char] = 1 return False return len(dif) == 2 and sum(dif) == 0 |