问题描述
小U 和 小R 各自拥有一个长度相等的二进制字符串 A 和 B。现在,他们想要将这两个字符串修改成相同的字符串。每次修改可以选择以下两种操作:
- 交换同一个字符串中的任意两个字符,交换操作的成本为它们索引之差的绝对值
|i - j|。 - 对某个字符进行取反操作,取反的成本为 2。
小U 和 小R 想知道,将字符串 A 和 B 修改为相同字符串的最小总成本是多少?
测试样例
样例1:
输入:
str1 = "10001",str2 = "10000"
输出:2
样例2:
输入:
str1 = "100100",str2 = "100001"
输出:2
样例3:
输入:
str1 = "1010",str2 = "0111"
输出:3
样例4:
输入:
str1 = "1100",str2 = "0011"
输出:4
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
int solution(const std::string &str1, const std::string &str2) {
int n = str1.length();
std::vector<int> diff_id;
// Find indices where strings differ
for (int i = 0; i < n; i++) {
if (str1[i] != str2[i]) {
diff_id.push_back(i);
}
}
int m = diff_id.size();
if (m == 0) {
return 0;
}
// Initialize dp array
std::vector<int> dp(m + 1, 0);
dp[1] = 2;
// Fill dp array
for (int i = 2; i <= m; i++) {
dp[i] = dp[i - 1] + 2;
if (i >= 2 && str1[diff_id[i - 2]] != str1[diff_id[i - 1]]) {
dp[i] = std::min(dp[i], dp[i - 2] + diff_id[i - 1] - diff_id[i - 2]);
}
if (i >= 4 && str1[diff_id[i - 3]] != str1[diff_id[i - 1]] &&
str1[diff_id[i - 4]] != str1[diff_id[i - 2]]) {
dp[i] = std::min(dp[i], dp[i - 4] + diff_id[i - 1] + diff_id[i - 2] -
diff_id[i - 3] - diff_id[i - 4]);
}
}
return dp[m];
}
int main() {
// Add your test cases here
std::cout << (solution("10001", "10000") == 2) << std::endl;
std::cout << (solution("100100", "100001") == 2) << std::endl;
std::cout << (solution("1010", "0011") == 3) << std::endl;
std::cout << (solution("1100", "0011") == 4) << std::endl;
return 0;
}