LeetCode 1247. Minimum Swaps to Make Strings Equals解题报告(python)

1247. Minimum Swaps to Make Strings Equal

  1. Minimum Swaps to Make Strings Equal python solution

题目描述

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.
在这里插入图片描述

解析

将s1和s2对应成字符对
Example 1:
s1 = “xx”
s2 = “yy”
在0和1两个索引位置,字符对均为x_y,只需要交换一次,使s1和s2相等
Example 2:
s1 = “yy”
s2 = “xx”
在0和1两个索引位置,字符对均为y_x,只需要交换一次,使s1和s2相等
Example 3:
s1 = “xy”
s2 = “yx”
在0这个索引位置,字符对为x_y。在1这个索引位置,字符对为y_x。所以需要交换两次,使s1和s2相等。
Example 4:
s1 = “xxyyxyxyxx”,
s2 = “xyyxyxxxyx”
首先移除掉在同一索引位置相同的元素,得到
s1 = “xyxyyx”
s2 = “yxyxxy”

“x_y” count = 3 (index 0, 2, 5)
“y_x” count = 3 (index 1, 3, 4)
如例子1,索引位置0和2只需要一次交换。如例子2,索引位置1和3需要一次交换。如例子3,索引位置5和4需要两次交换。所以一共需要四次交换。
故解题步骤如下:
计算字符对"x_y" and "y_x"的个数
如果两者的总和为奇数,直接返回-1,因为s1字符串和s2字符串中x,y的个数不相等
每两个x_y需要一次交换,每两个y_x需要一次交换
如果最后剩下一个x_y和y_x,那么再需要两次交换。

// An highlighted block
class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        x_y,y_x=0,0
        res=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:
            res+=2
        return res
           

Reference

https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/419874/Simply-Simple-Python-Solution-with-detailed-explanation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值