【Leetcode_总结】 859. 亲密字符串 -python

Q:

859. 亲密字符串

给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。

示例 1:

输入: A = "ab", B = "ba"
输出: true

示例 2:

输入: A = "ab", B = "ab"
输出: false

示例 3:

输入: A = "aa", B = "aa"
输出: true

 


链接:https://leetcode-cn.com/problems/buddy-strings/description/

思路:首先判断是否等长,不等长False,是否有空值,有空值False,等长的情况下看不同字符的数量,数量大于2的False 等于1的False,剩下的就是不同字符数量为2的 和两个字符串完全相同的情况,如果完全相同,看是否有两个以上的相同字符,有的话就是True 没有就是False 代码如下:

class Solution:
    def buddyStrings(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        if len(A) != len(B):
            return False
        if A == '' or B == '':
            return False
        temp = []
        count = 0
        for i in range(len(A)):
            if A[i] != B[i]:
                temp.append(A[i])
                temp.append(B[i])
                count += 1
        if count == 0:
            if len(list(set(A))) < len(A):
                return True
            else:
                return False
        elif count == 2:
            if temp[0] == temp[3] and temp[2] == temp[1]:
                return True
            else:
                return False
        else:
            return False

 【Leetcode_总结】 859. 亲密字符串 -python