859.亲密字符串

https://leetcode-cn.com/problems/buddy-strings/

要满足三个条件:长度相同,词频相同,不同位数恰好为2(只交换两个字符)。只要有一个不满足都不符合

此外,若不同位数为0要详细讨论,如s=ab,goal=ab,这样不能交换。能交换的情况是存在某个字符的频率>=2

class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        m, n = len(s), len(goal)
        # 长度不同直接返回
        if m != n:
            return False
        cntS, cntG = [0]*26, [0]*26	#表示字母a-z的词频
        diff = 0	# 不同的位数
        # 统计词频
        for a,b in zip(s, goal):
            cntS[ord(a) - ord('a')] += 1
            cntG[ord(b) - ord('a')] += 1
            if a != b:
                diff += 1
        for i in range(26):
            if cntS[i] != cntG[i]:	#某个字母词频不同直接返回
                return False
        # 此时长度和词频都一样
        if diff == 0:	# 特殊情况,看有无频率>=2的字符
            for i in range(26):
                if cntS[i] >= 2:
                    return True
            return False
        # 只有不同位数为2才符合,其余都不符
        if diff == 2:
            return True
        return False

最后更新于