[leetcode] 1247. Minimum Swaps to Make Strings Equal

Description

You are given two strings s1 and s2 of equal length consisting of letters “x” and “y” only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].

Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:

Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation: 
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

Example 2:

Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation: 
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.

Example 3:

Input: s1 = "xx", s2 = "xy"
Output: -1

Example 4:

Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4

Constraints:

  • 1 <= s1.length, s2.length <= 1000
  • s1, s2 only contain ‘x’ or ‘y’.

分析

题目的意思是:给定两个字符串,用最小的交换步骤是的两个字符串相等。这道题我觉得挺难的,第一,相同位置相等的字符不影响最小交换步骤的求解;另外,除此之外,最小交换步骤res=x_y/2+y_x/2 其中x_y为字符串1中不等于字符串2的x的个数,y_x则相反。如果(x_y+y_x)%2==1,说明不能通过交换构成两个相等的字符串;最后,如果x_y或者y_x是奇数的时候,最小交换步数需要+2。这些规律我也找不出来,我只是欣赏一下,哈哈哈。

代码

class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        x_y,y_x=0,0
        for c1,c2 in zip(s1,s2):
            if(c1!=c2):
                if(c1=='x'):
                    x_y+=1
                else:
                    y_x+=1
        if((x_y+y_x)%2==1):
            return -1
        res=x_y//2
        res+=y_x//2
        if(x_y%2==1):
            return res+2
        return res

参考文献

[LeetCode] Simply Simple Python Solution - with detailed explanation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值