参考问题这里
我们有两个字符串A和B,它们具有相同的字符集。我们需要更改这些字符串以获得两个相等的字符串。在每次移动中,我们可以执行以下操作之一:
1- 交换一个字符串的两个连续字符
2- 交换一个字符串的第一个和最后一个字符可以对任何一个字符串执行移动操作。我们需要多少次移动才能获得两个相等的字符串?输入格式和约束条件:输入的第一行和第二行包含两个字符串A和B。保证它们的字符集相等。1 <= length(A) = length(B) <= 2000。所有输入字符都在'a'和'z'之间。
看起来这需要使用动态规划来解决。但我无法想出方程式。有人在答案中提出了方程式-但看起来并不完全正确。
dp[i][j] =
Min{
dp[i + 1][j - 1] + 1, if str1[i] = str2[j] && str1[j] = str2[i]
dp[i + 2][j] + 1, if str1[i] = str2[i + 1] && str1[i + 1] = str2[i]
dp[i][j - 2] + 1, if str1[j] = str2[j - 1] && str1[j - 1] = str2[j]
}
In short, it's
dp[i][j] = Min(dp[i + 1][j - 1], dp[i + 2][j], dp[i][j - 2]) + 1.
Here dp[i][j] means the number of minimum swaps needs to swap str1[i, j] to str2[i, j]. Here str1[i, j] means the substring of str1 starting from pos i to pos j :)
Here is an example like the one in the quesition,
str1 = "aab",
str2 = "baa"
dp[1][1] = 0 since str1[1] == str2[1];
dp[0][2] = str1[0 + 1][2 - 1] + 1 since str1[0] = str2[2] && str1[2] = str2[0].