📌  相关文章
📜  检查是否可以通过交换相邻字符对使两个字符串相等(1)

📅  最后修改于: 2023-12-03 15:10:54.510000             🧑  作者: Mango

检查是否可以通过交换相邻字符对使两个字符串相等

有两个字符串s1和s2,判断它们是否可以通过交换s1中的两个字符得到s2,如果可以,返回true,否则返回false。

解题思路
  1. 先判断两个字符串的长度是否相等,如果不相等,则不可能通过交换s1中的两个字符得到s2,直接返回false;
  2. 统计s1和s2中每个字符出现的次数,如果它们不一致,也不可能通过交换s1中的两个字符得到s2,直接返回false;
  3. 遍历s1和s2,统计不同位置的字符对数,如果大于2,则不可能通过交换s1中的两个字符得到s2,直接返回false;
  4. 如果字符对数为0或2,则返回true,否则返回false。
代码实现
def can_swap(s1: str, s2: str) -> bool:
    if len(s1) != len(s2):
        return False

    count1 = {}
    count2 = {}
    for c1, c2 in zip(s1, s2):
        count1[c1] = count1.get(c1, 0) + 1
        count2[c2] = count2.get(c2, 0) + 1
    if count1 != count2:
        return False

    diff = 0
    for c1, c2 in zip(s1, s2):
        if c1 != c2:
            diff += 1
            if diff > 2:
                return False

    return diff == 0 or diff == 2
测试示例
assert can_swap("abcd", "bacd") is True
assert can_swap("abcd", "abce") is False
assert can_swap("", "") is True
assert can_swap("a", "a") is True
assert can_swap("aa", "aa") is True
assert can_swap("ab", "ba") is True
assert can_swap("ab", "bc") is False
assert can_swap("abcd", "dcba") is False