代码改变世界

[LeetCode] 859. Buddy Strings_Easy

2018-08-20 09:59  Johnson_强生仔仔  阅读(244)  评论(0编辑  收藏  举报

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.

题目思路就是先用length来初步判断, 然后如果相等的话要看是否有重复的元素, 如果有那就可以, 否则不行, 比如aa, aa可以, ab, ab不行. 如果不等, 就要他们不同的地方正好两个, 并且交换顺序, 正好相等. 

Code      T: O(n)    S; O(n)    but if contains lower cases, then at most will be 26 , so you can explain it is O(1).

class Solution:
    def buddyStrings(self, A, B):
        la, lb = len(A), len(B)
        if la != lb: return False
        if A == B:
            return any(val > 1 for val in collections.Counter(A).values())
        ans = [None] * 2
        for i in range(la):
            if A[i] != B[i]:
                if ans[1]:
                    return False
                elif ans[0]:
                    ans[1]= A[i] + B[i]
                else:
                    ans[0]= B[i] + A[i]
        return ans[0] and ans[1] and ans[0] == ans[1]