LeetCode题解(0859):判断两字符串是否为亲密字符串(Python)

题目:原题链接(简单)

标签:字符串

解法时间复杂度空间复杂度执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1)40ms (83.03%)
Ans 2 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1)40ms (83.03%)
Ans 3 (Python)

解法一:

def buddyStrings(self, A: str, B: str) -> bool:
    if len(A) != len(B):
        return False

    differ = []
    for i in range(len(A)):
        if A[i] != B[i]:
            differ.append(i)

    if len(differ) == 2:
        return A[differ[0]] == B[differ[1]] and A[differ[1]] == B[differ[0]]
    elif len(differ) == 0:
        return len(set(A)) < len(A)
    else:
        return False

解法二(整理解法一的逻辑):

def buddyStrings(self, A: str, B: str) -> bool:
    if A == B:
        return len(set(A)) < len(A)
    else:
        if len(A) != len(B):
            return False
        differ = []
        for i in range(len(A)):
            if A[i] != B[i]:
                differ.append(i)
        return len(differ) == 2 and A[differ[0]] == B[differ[1]] and A[differ[1]] == B[differ[0]]
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页