我有像xxoxxooo这样的字符串,我想把它编辑成这种形式xoxoxoxo,我的问题是如何找到最小数量的交换,我只能交换2个邻居作为交换。我想通过字符串找到最接近的冗余x并将其移动到当前位置但是我认为这太慢了,因为字符串可以有1e6 * 2个字符。有什么想法吗?
答案 0 :(得分:2)
让我们在s_i
和i
之间交换i+1
假设您有一个从S = s_{i1} s_{i2} ...
到A
的最小交换序列B
。因为它很小,所以只能将x
与o
交换,而x
与x
或o
与o
交换。因此,S
的操作是将o
的{{1}} A
发送到o
的{{1}},B
o
A
1}}到o
的第二个B
,依此类推。因此,交换次数不能小于
Sum_i abs(pos of i-st o in A - pos of i-st o in B)
现在很容易找到具有这个交换次数的序列,因此这是正确的值。
这是一个计算它的算法
Input: s1 and s2 of common length n
I'm assuming that they contains the same number of 'x' and 'o'
res = 0;
i1 = 0; i2 = 0;
while true do
// find the next o
while i1 < n and s1[i1] == 'x' do
i1++
if i1 == n return res
// no check that i2 < n because of assumption
while s2[i2] == 'x' do
i2++
res += abs(i1-i2)
i1++; i2++
答案 1 :(得分:0)
您可以忽略其中一种字符,并计算每种其他类型字符与每个目标位置的距离。
更具体地说,所选择的字符类型的第i次出现将始终被映射到第i个目标位置 - 将其移动经过该点是多余的(因为我们将交换两个相同的位置)在某一点键入),如果它没有移动到那里,那么在其中一侧就没有足够的那种类型的字符。此外,由于我们只能交换相邻的字符,因此我们会采取一些等于精确距离的移动来将字符移到某个位置。
这可以通过以下算法完成:(伪代码)
distance = 0
pos = 0
for i = 0 to n
if i == 'x' // only check 'x's
distance += abs(i - pos) // calculate distance to target position
pos += 2 // move to the next position
对于你的例子:
index 0 1 2 3 4 5 6 7
character x x o x x o o o
distance 0 0 1 1 2 4 4 4 4
pos 0 2 4 4 6 8 8 8 8
所以距离是4。