📌  相关文章
📜  在N个字符的字符串中插入两对括号的方式的数目

📅  最后修改于: 2021-04-26 07:08:17             🧑  作者: Mango

给定长度为N的字符串str ,任务是找到在给定的字符串仅插入2对括号的方法,以使所得字符串仍然有效。
例子:

方法:可以观察到,对于字符串1、2、3,…,N的长度,一系列将形成为1、6、20、50、105、196、336、540,…,N项是(N + 1) 2 *((N + 1) 2 – 1)/ 12
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the number of ways
// to insert the bracket pairs
int cntWays(string str, int n)
{
    int x = n + 1;
    int ways = x * x * (x * x - 1) / 12;
    return ways;
}
 
// Driver code
int main()
{
    string str = "ab";
    int n = str.length();
 
    cout << cntWays(str, n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the number of ways
// to insert the bracket pairs
static int cntWays(String str, int n)
{
    int x = n + 1;
    int ways = x * x * (x * x - 1) / 12;
    return ways;
}
 
// Driver code
public static void main(String []args)
{
    String str = "ab";
    int n = str.length();
 
    System.out.println(cntWays(str, n));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function to return the number of ways
# to insert the bracket pairs
def cntWays(string, n) :
 
    x = n + 1;
    ways = x * x * (x * x - 1) // 12;
    return ways;
 
# Driver code
if __name__ == "__main__" :
 
    string = "ab";
    n = len(string);
 
    print(cntWays(string, n));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
class GFG
{
 
// Function to return the number of ways
// to insert the bracket pairs
static int cntWays(String str, int n)
{
    int x = n + 1;
    int ways = x * x * (x * x - 1) / 12;
    return ways;
}
 
// Driver code
public static void Main(String []args)
{
    String str = "ab";
    int n = str.Length;
 
    Console.WriteLine(cntWays(str, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
6