:给出2 个 字符串,每个字符串只包含0和1 ,我们对第二个字符串可以做一种操作,就是交换两个相邻字符,经过多少次操作,第二个字符串可以变成第一个,如果不能输出-1

img


:给出2 个 字符串,每个字符串只包含0和1 ,我们对第二个字符串可以做一种操作,就是交换两个相邻字符,经过多少次操作,第二个字符串可以变成第一个,如果不能输出-1
谢谢啦

稍等,帮你写一个

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str1, str2;
    cin >> str1 >> str2;

    if (str1.size() != str2.size()) {
        cout << "-1" << endl;
        return 0;
    }

    int cnt = 0;
    for (int i = 0; i < str1.size(); i++) {
        if (str1[i] != str2[i]) {
            int j = i + 1;
            while (j < str2.size() && str2[j] != str1[i]) {
                j++;
            }
            if (j == str2.size()) {
                cout << "-1" << endl;
                return 0;
            }
            while (j > i) {
                swap(str2[j], str2[j-1]);
                j--;
                cnt++;
            }
        }
    }
    cout << cnt << endl;
    return 0;
}

至少两个字符串中0和1的数量相等才可能通过交换变成一样的

相等怎么替换啊