洞察如何通过ios app灵活实现微信小程序的跨平台管理
890
2022-10-03
LeetCode-1247. Minimum Swaps to Make Strings Equal
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: 1Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"Output: 2Explanation: 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 <= 1000s1, s2 only contain'x' or'y'.
题解:
不会,看了解答也想不通那种,可能我脑子有问题吧。
class Solution {public: int minimumSwap(string s1, string s2) { int l1 = s1.length(), l2 = s2.length(); if (l1 != l2) { return -1; } int xy = 0, yx = 0; for (int i = 0; i < l1; i++) { if (s1[i] != s2[i]) { if (s1[i] == 'x') { xy++; } else { yx++; } } } if ((xy + yx) % 2 != 0) { return -1; } return xy / 2 + yx / 2 + (xy % 2) * 2; }};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~