题目
交换字符串使得字符串相同
思路分析
- 因为字符串里面只有x,y两种字符。我们需要统计不同位置上x,y的个数
- 交换先有限同类交换,也就是对于都是xy类型,(s1:xx,s2:yy)或者yx类型(s1:yy s2:xx。
- 如果交换完同类,发现还有剩余,交换xy和yx类型,需要2次。
代码
class Solution {
public:
int minimumSwap(string s1, string s2) {
int tot1 = 0, tot2 = 0,ans = 0;
for(int i = 0;i < s1.size();i++){
if(s1[i] == 'x' && s2[i] == 'y') tot1++;
else if(s1[i] == 'y' && s2[i] == 'x') tot2++;
}
ans += tot1 / 2 + tot2 / 2;
if(tot1 % 2 == 0&& tot2 % 2 == 0) return ans;
else if(tot1 % 2 == 1 && tot2 % 2 == 1) return ans + 2;
else return -1;
}
};