给定长度为n的字符串S表示彼此相邻的n个盒子。
- 索引i处的字符R表示第i个框被推向右侧。
- 另一方面,索引i处的L表示第i个框被推向左侧。
- 还有一个。代表一个空白空间。
我们从初始配置开始,在每个时间单位上,将一个盒子向右推都会将下一个盒子推向右边,对于将一个盒子推向左边也是如此。任务是在无法再移动时打印所有盒子的最终位置。如果存在子字符串“ RL”,则正从两个方向推动中间框,因此不再移动。
例子:
Input: S = “RR.L”
Output: RR.L
The first and second boxes are being toward right. The middle dot is being pushed from both directions, so does not move.
Input: S = “R..R…L.”
Output: RRRRR.LL.
At time unit 1 :
The first box pushes second box.
Third box pushes fourth box.
Second last box pushes third last box, configuration becomes
“RR.RR.LL.”
At time unit 2 :
Second box pushes third box, string becomes
“RRRRR.LL.”
方法:我们可以计算施加在每个盒子上的净力。我们关心的力是盒子离左R或右L的距离,即距离我们越近,该力越强。
- 从左向右扫描,力在每次迭代中衰减1 ,如果再次遇到R ,则力重置为N。
- 同样,从右到左方向,我们可以从右(接近L )找到力。
- 对于某些盒结果[i],如果力相等,则结果为。双方都施加相同的力量。否则,无论哪个力强,都暗示着我们的结果。
For string S = “R..R…L.”
The forces going from left to right are [7, 6, 5, 7, 6, 5, 4, 0, 0].
The forces going from right to left are [0, 0, 0, 0, -4, -5, -6, -7, 0].
Combining them (taking their arithmetic addition at each index) gives result = [7, 6, 5, 7, 2, 0, -2, -7, 0].
Thus, the final answer is RRRRR.LL.
下面是上述方法的实现:
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..