跳过正文
  1. leetcode 题解/

1790_仅执行一次字符串交换能否使两个字符串相等

·85 字·1 分钟

类型:字符串

    1. 仅执行一次字符串交换能否使两个字符串相等 💚

    https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal/

    ❓ 给你两个长度相等的字符串,如果对 其中一个字符串执行最多一次字符交换(交换字符串中两个字符的位置)就可以使两个字符串相等,返回 true ;否则,返回 false 。

    💡 一次遍历

    使用两个指针,同步遍历这两个字符串。如果符合要求的话,应该会正好找到两处错位。

    class Solution:
        def areAlmostEqual(self, s1: str, s2: str) -> bool:
            firstDiff = []
            secondDiff = []
            for i in range(len(s1)):
                diff = ord(s1[i]) - ord(s2[i])
                if diff == 0:
                    continue
                if not firstDiff:
                    firstDiff = [s1[i], s2[i]]
                elif not secondDiff:
                    secondDiff = [s1[i], s2[i]]
                else:
                    return False
            if firstDiff and not secondDiff:
                return False
            if not firstDiff and not secondDiff:
                return True
            return firstDiff[0] == secondDiff[1] and firstDiff[1] == secondDiff[0]

    时间复杂度:O(n),空间复杂度:O(1)