链接:https://leetcode-cn.com/problems/minimum-swaps-to-make-strings-equal/
字符串在某一位置不匹配仅有两种情况,
s
1
s_1
s1中为
y
y
y,
s
2
s_2
s2中为
x
x
x,或者反过来。分别记录
y
x
yx
yx与
x
y
xy
xy的出现次数,两个同类的不匹配可以通过一次交换解决,两个不同类的不匹配可以通过两次交换解决。
C++代码:
class Solution {
public:
int minimumSwap(string s1, string s2) {
int type1 = 0;
int type2 = 0;
for(int i = 0;i<s1.size();i++)
{
if(s1[i] =='x'&&s2[i] == 'y')
type1++;
else if(s1[i] == 'y'&&s2[i] =='x')
type2++;
}
if((type1+type2)%2==1)
return -1;
return type1/2+type2/2 +type1%2+type2%2;
}
};
本文解析了LeetCode上一道关于字符串匹配的问题,探讨了如何通过记录特定字符组合的出现次数来解决字符串相等问题,提供了C++代码实现,并讨论了解决方案的有效性和效率。
621

被折叠的 条评论
为什么被折叠?



