📜  修改后字符串的最终状态

📅  最后修改于: 2021-04-24 18:06:23             🧑  作者: Mango

给定长度为n的字符串S表示彼此相邻的n个盒子。

  1. 索引i处的字符R表示第i个框被推向右侧。
  2. 另一方面,索引i处的L表示第i个框被推向左侧。
  3. 还有一个代表一个空白空间。

我们从初始配置开始,在每个时间单位上,将一个盒子向右推都会将下一个盒子推向右边,对于将一个盒子推向左边也是如此。任务是在无法再移动时打印所有盒子的最终位置。如果存在子字符串“ RL”,则正从两个方向推动中间框,因此不再移动。

例子:

方法:我们可以计算施加在每个盒子上的净力。我们关心的力是盒子离左R或右L的距离,即距离我们越近,该力越强。

  • 从左向右扫描,力在每次迭代中衰减1 ,如果再次遇到R ,则力重置为N。
  • 同样,从右到左方向,我们可以从右(接近L )找到力。
  • 对于某些盒结果[i],如果力相等,则结果为双方都施加相同的力量。否则,无论哪个力强,都暗示着我们的结果。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function to return final
// positions of the boxes
string pushBoxes(string S)
{
    int N = S.length();
    vector force(N, 0);
 
    // Populate forces going
    // from left to right
    int f = 0;
    for(int i = 0; i < N; i++)
    {
        if (S[i] == 'R')
        {
            f = N;
        }
        else if (S[i] == 'L')
        {
            f = 0;
        }
        else
        {
            f = max(f - 1, 0);
        }
        force[i] += f;
    }
 
    // Populate forces going from right to left
    f = 0;
    for(int i = N - 1; i >= 0; i--)
    {
        if (S[i] == 'L')
        {
            f = N;
        }
        else if (S[i] == 'R')
        {
            f = 0;
        }
        else
        {
            f = max(f - 1, 0);
        }
        force[i] -= f;
    }
 
    // return final state of boxes
    string ans;
    for(int f : force)
    {
        ans += f == 0 ? '.' : f > 0 ? 'R' : 'L';
    }
    return ans;
}
 
// Driver code
int main()
{
    string S = ".L.R...LR..L..";
     
    // Function call to print answer
    cout << pushBoxes(S);
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 implementation of above approach
 
# Function to return final
# positions of the boxes
def pushBoxes(S):
 
    N = len(S)
    force = [0] * N
 
    # Populate forces going from left to right
    f = 0
    for i in range(0, N):
 
        if S[i] == 'R':
            f = N
        elif S[i] == 'L':
            f = 0
        else:
            f = max(f - 1, 0)
        force[i] += f
 
    # Populate forces going from right to left
    f = 0
    for i in range(N - 1, -1, -1):
 
        if S[i] == 'L':
            f = N
        elif S[i] == 'R':
            f = 0
        else:
            f = max(f - 1, 0)
        force[i] -= f
 
    # return final state of boxes
    return "".join('.' if f == 0 else 'R' if f > 0 else 'L'
                   for f in force)
 
 
# Driver code
S = ".L.R...LR..L.."
 
# Function call to print answer
print(pushBoxes(S))


输出:
LL.RR.LLRRLL..