859. 亲密字符串

exiaohu 于 2021-11-23 发布

题目链接:859. 亲密字符串

from collections import Counter


class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        if len(s) != len(goal):
            return False

        s_counter, goal_counter = Counter(s), Counter(goal)
        if s_counter != goal_counter:
            return False

        (_, n), = s_counter.most_common(1)
        if s == goal and n > 1:
            return True

        return len([(a, b) for a, b in zip(s, goal) if a != b]) == 2