📅  最后修改于: 2023-12-03 15:10:54.510000             🧑  作者: Mango
有两个字符串s1和s2,判断它们是否可以通过交换s1中的两个字符得到s2,如果可以,返回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