leetcode 1790. Check if One String Swap Can Make Strings Equal (python)

该博客讨论了一种检查是否可以通过在一个字符串中进行一次字符串交换使两个等长字符串变得相等的算法。通过比较字符串并计数不同字符,可以确定是否可能在最多一次交换后使它们相等。如果字符串已经相等或仅需交换一对字符即可匹配,则返回True,否则返回False。该算法具有高效的运行时间和内存使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Example 1:

Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".	

Example 2:

Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.

Example 3:

Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.

Example 4:

Input: s1 = "abcd", s2 = "dcba"
Output: false

Note:

1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1 and s2 consist of only lowercase English letters.

解析

根据题意,就是将 s1 和 s2 能够在最多交换任意两个字符后变一样,就返回 True ,否则返回 False 。思路简单,就是先判断两个字符串是否相等,相等直接返回 True ,否则再用计数器记录各自包含的字符的出现次数,如果不相等直接返回 False 。如果仍无法判断,则再遍历两个字符串,如果相同索引下的字符不相等次数大于等于 3 则返回 False ,否则为 True 。

解答

class Solution(object):
    def areAlmostEqual(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        if s1 == s2:
            return True
        a = collections.Counter(s1)
        b = collections.Counter(s2)
        if a!=b:
            return False
        r = 0
        for i in range(len(s1)):
            if s1[i] != s2[i]:
                r += 1
        return r < 3            	      

运行结果

Runtime: 20 ms, faster than 52.90% of Python online submissions for Check if One String Swap Can Make Strings Equal.
Memory Usage: 13.5 MB, less than 59.65% of Python online submissions for Check if One String Swap Can Make Strings Equal.

原题链接:https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/

您的支持是我最大的动力

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值