贪心消消乐,上x下y的结构以及上y下x的结构,其中2+2的结构使用俩次就能够换掉
某一结构2个的也能使用一次换掉,1+1的结构只能通过俩次换掉’
class Solution {
public:
int minimumSwap(string s1, string s2) {
int xy = 0, yx = 0;//统计同一位置,上面x下面y以及上面y下面x的结构
int res= 0;
for (int i = 0; i < s1.size(); i++)
{
if (s1[i] != s2[i])
{
if (s1[i] == 'x' && s2[i] == 'y')
xy++;
if (s1[i] == 'y' && s2[i] == 'x')
yx++;
}
}
if ((xy + yx) % 2 != 0)//如果成奇数,这肯定不在方法
return -1;
while((xy - 2) >= 0 && (yx - 2) >= 0)//然后依次按照贪心的方式消消乐
{
res += 2;
xy -= 2;
yx -= 2;
}
while((xy - 2) >= 0)
{
res += 1;
xy -= 2;
}
while((yx - 2) >= 0)
{
res += 1;
yx -= 2;
}
while((xy - 1) >= 0 && (yx - 1) >= 0)
{
res += 2;
xy -= 1;
yx -= 1;
}
return res;
}
};