给定 N 个球在一条线上。每个球的初始方向由仅由“L”和“R”组成的字符串表示,分别代表左右方向。假设碰撞后两个球都改变了方向,碰撞前后速度将保持不变。计算发生碰撞的总数。
例子:
Input: str = "RRLL"
Output: 4
Explanation
After first collision: RLRL
After second collision: LRRL
After third collision: LRLR
After fourth collision: LLRR
Input: str = "RRLR"
Output: 2
Explanation
After first collision: RLRR
After second collision: LRRR
方法:
在每个阶段,我们必须找到子串“RL”的编号,将子串“RL”更改为“LR”,并再次计算结果字符串中子串“RL”的编号,然后重复以下直到没有子串“ RL”可用。我们不会在每个阶段计算子串“RL”的数量,因为它会消耗大量时间。另一种方法是,观察我们在每个阶段看到的结果字符串->“RRLL”->“RLRL”->“LRLR”->“LLRR”。
初始字符串是“RRLL”。让我们有一个方向为 L 的第三个球。现在观察这个 L 正在向字符串的左侧移动。当我们将“RL”交换为“LR”时,我们将把 L 移向完整字符串的左侧。现在类似地,如果我们继续这种交换,这个 L 将面对出现在该字符串左侧的每个 R,因此再次形成“RL”。因此,对于这个 L,“RL”的总数将是出现在该特定 L 左侧的 R 的总数。我们将对每个 L 重复此操作。因此,一般来说,为了计算每一个可能的在每个阶段的子串“RL”,我们将计算每个 L 左侧的表示总数,因为这些 R 和 L 将在每个阶段形成“RL”,这可以以线性时间复杂度完成。
下面是上述方法的实现:
C++
// C++ implementation to Find total
// no of collisions taking place between
// the balls in which initial direction
// of each ball is given
#include
using namespace std;
// Function to count no of collision
int count(string s)
{
int N, i, cnt = 0, ans = 0;
// length of the string
N = s.length();
for (i = 0; i < N; i++) {
if (s[i] == 'R')
cnt++;
if (s[i] == 'L')
ans += cnt;
}
return ans;
}
// Driver code
int main()
{
string s = "RRLL";
cout << count(s) << endl;
return 0;
}
Java
// Java implementation to Find total
// no of collisions taking place between
// the balls in which initial direction
// of each ball is given
import java.io.*;
class GFG {
// Function to count
// no of collision
static int count(String s)
{
int N, i, cnt = 0, ans = 0;
// length of the string
N = s.length();
for (i = 0; i < N; i++)
{
if (s.charAt(i) == 'R')
cnt++;
if (s.charAt(i) == 'L')
ans += cnt;
}
return ans;
}
// Driver code
static public void main(String[] args)
{
String s = "RRLL";
System.out.println(count(s));
}
}
// This code is contributed by Rutvik_56
Python3
# Python3 implementation to find total
# no of collisions taking place between
# the balls in which initial direction
# of each ball is given
# Function to count no of collision
def count(s):
cnt, ans = 0, 0
# Length of the string
N = len(s)
for i in range(N):
if (s[i] == 'R'):
cnt += 1
if (s[i] == 'L'):
ans += cnt
return ans
# Driver code
s = "RRLL"
print( count(s))
# This code is contributed by chitranayal
C#
// C# implementation to Find total
// no of collisions taking place between
// the balls in which initial direction
// of each ball is given
using System;
class GFG{
// Function to count no of collision
static int count(String s)
{
int N, i, cnt = 0, ans = 0;
// length of the string
N = s.Length;
for(i = 0; i < N; i++)
{
if (s[i] == 'R')
cnt++;
if (s[i] == 'L')
ans += cnt;
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
String s = "RRLL";
Console.Write(count(s));
}
}
// This code is contributed by shivanisinghss2110
Javascript
输出:
4