Leetcode 859 Buddy Strings

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 = “aa”, B = “aa”
Output: true

Example 4:
Input: A = “aaaaaaabc”, B = “aaaaaaacb”
Output: true

Example 5:
Input: A = “”, B = “aa”
Output: false

Note:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.

分析:

  1. 先判断是不是组成相同
  2. 在判断不同的个数是2还是0
  3. 如果是0,判断A中有没有相同字符

思路:
如果仔细写应该能写优美一点把,但是瑞了,不想写了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if collections.Counter(A) != collections.Counter(B):
return False
cnt = 0
for i in range(len(A)):
if A[i] != B[i]:
cnt += 1
if cnt > 2: return False
if cnt == 0:
return len(set(A)) != len(A)
return cnt == 2


O(n) time, O(n) space
20 / 20 test cases passed.
difficulty: easy
Runtime: 78 ms