📜  计算给定字符串的括号分数

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

给定长度为N的字符串str (由成对的圆括号组成),任务是根据给定的规则计算给定字符串的分数:

  • “()”的得分为1
  • “ a b”的得分为a + b ,其中ab是成对的平衡括号。
  • “(a)”的得分是a的两倍,即得分是a的2 *得分

例子:

基于的方法:有关基于的方法,请参阅本文的上一篇文章。
时间复杂度: O(N)
辅助空间: O(N)

基于堆栈的方法:想法是遍历字符串,而在遍历字符串str时,如果遇到括号‘)’ ,则计算这对括号的分数。请按照以下步骤解决问题:

  • 初始化一个堆栈,例如S ,以跟踪得分,并最初将0推入堆栈。
  • 使用变量i遍历字符串str并执行以下步骤:
    • 如果str [i]的值等于‘(’ ,则将0压入堆栈S。
    • 否则,请执行以下步骤:
      • 将堆栈S的顶部存储在一个名为temp的变量中,然后从堆栈顶部弹出该元素。
      • 如果temp的值不为零,则存在内部括号。将2 * temp添加到堆栈的顶部。否则,将1添加到堆栈的顶部。
  • 完成上述步骤后,打印堆栈顶部的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate the score
// of the parentheses using stack
void scoreOfParentheses(string s)
{
    // To keep track of the score
    stack stack;
 
    // Initially, push 0 to stack
    stack.push(0);
 
    // Traverse the string s
    for (char c : s) {
 
        // If '(' is encountered,
        // then push 0 to stack
        if (c == '(')
            stack.push(0);
 
        // Otherwise
        else {
 
            // Balance the last '(', and store
            // the score of inner parentheses
            int tmp = stack.top();
            stack.pop();
 
            int val = 0;
 
            // If tmp is not zero, it means
            // inner parentheses exists
            if (tmp > 0)
                val = tmp * 2;
 
            // Otherwise, it means no
            // inner parentheses exists
            else
                val = 1;
 
            // Pass the score of this level
            // to parent parentheses
            stack.top() += val;
        }
    }
 
    // Print the score
    cout << stack.top();
}
 
// Driver Code
int main()
{
    string S = "(()(()))";
    scoreOfParentheses(S);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to calculate the score
  // of the parentheses using stack
  static void scoreOfParentheses(String s)
  {
     
    // To keep track of the score
    Stack stack = new Stack<>();
 
    // Initially, push 0 to stack
    stack.push(0);
 
    // Traverse the string s
    for (char c : s.toCharArray()) {
 
      // If '(' is encountered,
      // then push 0 to stack
      if (c == '(')
        stack.push(0);
 
      // Otherwise
      else {
 
        // Balance the last '(', and store
        // the score of inner parentheses
        int tmp = stack.pop();
 
        int val = 0;
 
        // If tmp is not zero, it means
        // inner parentheses exists
        if (tmp > 0)
          val = tmp * 2;
 
        // Otherwise, it means no
        // inner parentheses exists
        else
          val = 1;
 
        // Pass the score of this level
        // to parent parentheses
        stack.push(stack.pop() + val);
      }
    }
 
    // Print the score
    System.out.println(stack.peek());
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    String S = "(()(()))";
 
    // Function call
    scoreOfParentheses(S);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python 3 program for the above approach
 
# Function to calculate the score
# of the parentheses using stack
def scoreOfParentheses(s):
   
    # To keep track of the score
    stack = []
 
    # Initially, push 0 to stack
    stack.append(0)
 
    # Traverse the string s
    for c in s:
       
        # If '(' is encountered,
        # then push 0 to stack
        if (c == '('):
            stack.append(0)
 
        # Otherwise
        else:
           
            # Balance the last '(', and store
            # the score of inner parentheses
            tmp = stack[len(stack) - 1]
            stack = stack[:-1]
 
            val = 0
 
            # If tmp is not zero, it means
            # inner parentheses exists
            if (tmp > 0):
                val = tmp * 2
 
            # Otherwise, it means no
            # inner parentheses exists
            else:
                val = 1
 
            # Pass the score of this level
            # to parent parentheses
            stack[len(stack) - 1] += val
 
    # Print the score
    print(stack[len(stack) - 1])
 
# Driver Code
if __name__ == '__main__':
    S = "(()(()))"
    scoreOfParentheses(S)
     
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to calculate the score
  // of the parentheses using stack
  static void scoreOfParentheses(String s)
  {
     
    // To keep track of the score
    Stack stack = new Stack();
 
    // Initially, push 0 to stack
    stack.Push(0);
 
    // Traverse the string s
    foreach (char c in s.ToCharArray()) {
 
      // If '(' is encountered,
      // then push 0 to stack
      if (c == '(')
        stack.Push(0);
 
      // Otherwise
      else {
 
        // Balance the last '(', and store
        // the score of inner parentheses
        int tmp = stack.Pop();
 
        int val = 0;
 
        // If tmp is not zero, it means
        // inner parentheses exists
        if (tmp > 0)
          val = tmp * 2;
 
        // Otherwise, it means no
        // inner parentheses exists
        else
          val = 1;
 
        // Pass the score of this level
        // to parent parentheses
        stack.Push(stack.Pop() + val);
      }
    }
 
    // Print the score
    Console.WriteLine(stack.Peek());
  }
 
  // Driver code
  public static void Main(String[] args)
  {
 
    String S = "(()(()))";
 
    // Function call
    scoreOfParentheses(S);
  }
}
 
// This code is contributed by 29AjayKumar


输出:
6

时间复杂度: O(N)
辅助空间: O(N)