📜  计算由平衡括号组成的字符串的分数

📅  最后修改于: 2021-09-02 06:01:33             🧑  作者: Mango

给定一个由一对平衡括号组成的字符串str ,任务是根据以下规则计算给定字符串的分数:

  1. () ”的得分为 1。
  2. xy ” 的分数为x + y ,其中xy是单独的一对平衡括号。
  3. (x) ”的得分是x 的两倍(即), x 的 2 * 得分

例子:

方法:使用Stack可以解决这个问题。我们的想法是遍历字符串的字符。对于每个i字符,检查字符是否为‘(‘ 。如果为真,则将该字符插入堆栈。否则,计算内括号的分数并将分数的两倍插入堆栈。遵循解决问题的步骤如下:

  • 初始化一个堆栈来存储当前遍历的字符或内平衡括号的分数。
  • 迭代字符串str的字符。对于每个i字符,检查以下条件:
    • 如果当前字符是否为‘(‘ 。如果发现为真,则将当前字符压入堆栈。
    • 否则,检查栈顶元素是否为‘(‘ 。如果发现为真,则将“1”插入栈中,代表内平衡括号的分数。
    • 否则,将堆栈的顶部元素加倍并将获得的值压入堆栈。
  • 最后,打印得到的总分。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
#include 
using namespace std;
 
// Function to calculate
// score of parentheses
long long scoreOfParentheses(string S)
{
 
    stack s;
 
    // Stores index of
    // character of string
    int i = 0;
 
    // Stores total scores
    // obtained from the string
    long long ans = 0;
 
    // Iterate over characters
    // of the string
    while (i < S.length()) {
 
        // If s[i] is '('
        if (S[i] == '(')
            s.push("(");
        else {
 
            // If top element of
            // stack is '('
            if (s.top() == "(") {
                s.pop();
                s.push("1");
            }
            else {
 
                // Stores score of
                // inner parentheses
                long long count = 0;
 
                // Calculate score of
                // inner parentheses
                while (s.top() != "(") {
 
                    // Update count
                    count += stoi(s.top());
                    s.pop();
                }
 
                // Pop from stack
                s.pop();
 
                // Insert score of
                // inner parentheses
                s.push(to_string(2 * count));
            }
        }
 
        // Update i
        i++;
    }
 
    // Calculate score
    // of the string
    while (!s.empty()) {
 
        // Update ans
        ans += stoi(s.top());
        s.pop();
    }
    return ans;
}
 
// Driver Code
int main()
{
    string S1 = "(()(()))";
    cout << scoreOfParentheses(S1) << endl;
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
  // Function to calculate
  // score of parentheses
  static long scoreOfParentheses(String S)
  {
    Stack s = new Stack<>();
 
    // Stores index of
    // character of String
    int i = 0;
 
    // Stores total scores
    // obtained from the String
    long ans = 0;
 
    // Iterate over characters
    // of the String
    while (i < S.length())
    {
 
      // If s[i] is '('
      if (S.charAt(i) == '(')
        s.add("(");
      else
      {
 
        // If top element of
        // stack is '('
        if (s.peek() == "(")
        {
          s.pop();
          s.add("1");
        }
        else
        {
 
          // Stores score of
          // inner parentheses
          long count = 0;
 
          // Calculate score of
          // inner parentheses
          while (s.peek() != "(")
          {
 
            // Update count
            count += Integer.parseInt(s.peek());
            s.pop();
          }
 
          // Pop from stack
          s.pop();
 
          // Insert score of
          // inner parentheses
          s.add(String.valueOf(2 * count));
        }
      }
 
      // Update i
      i++;
    }
 
    // Calculate score
    // of the String
    while (!s.isEmpty())
    {
 
      // Update ans
      ans += Integer.parseInt(s.peek());
      s.pop();
    }
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S1 = "(()(()))";
    System.out.print(scoreOfParentheses(S1) +"\n");
  }
}
 
// This code is contributed by 29AjayKumar.


Python3
# Python3 program to implement
# the above approach
 
# Function to calculate
# score of parentheses
def scoreOfParentheses(S):
    s = []
 
    # Stores index of
    # character of string
    i = 0
 
    # Stores total scores
    # obtained from the string
    ans = 0
 
    # Iterate over characters
    # of the string
    while (i < len(S)):
 
        # If s[i] is '('
        if (S[i] == '('):
            s.append("(")
        else:
 
            # If top element of
            # stack is '('
            if (s[-1] == "("):
                s.pop()
                s.append("1")
            else:
 
                # Stores score of
                # inner parentheses
                count = 0
 
                # Calculate score of
                # inner parentheses
                while (s[-1] != "("):
 
                    # Update count
                    count += int(s[-1])
                    s.pop()
 
                # Pop from stack
                s.pop()
 
                # Insert score of
                # inner parentheses
                s.append(str(2 * count))
 
        # Update i
        i += 1
 
    # Calculate score
    # of the string
    while len(s) > 0:
 
        # Update ans
        ans += int(s[-1])
        s.pop()
    return ans
   
# Driver Code
if __name__ == '__main__':
    S1 = "(()(()))"
    print(scoreOfParentheses(S1))
 
    # This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to calculate
  // score of parentheses
  static long scoreOfParentheses(String S)
  {
    Stack s = new Stack();
 
    // Stores index of
    // character of String
    int i = 0;
 
    // Stores total scores
    // obtained from the String
    long ans = 0;
 
    // Iterate over characters
    // of the String
    while (i < S.Length)
    {
 
      // If s[i] is '('
      if (S[i] == '(')
        s.Push("(");
      else
      {
 
        // If top element of
        // stack is '('
        if (s.Peek() == "(")
        {
          s.Pop();
          s.Push("1");
        }
        else
        {
 
          // Stores score of
          // inner parentheses
          long count = 0;
 
          // Calculate score of
          // inner parentheses
          while (s.Peek() != "(")
          {
 
            // Update count
            count += Int32.Parse(s.Peek());
            s.Pop();
          }
 
          // Pop from stack
          s.Pop();
 
          // Insert score of
          // inner parentheses
          s.Push(String.Join("", 2 * count));
        }
      }
 
      // Update i
      i++;
    }
 
    // Calculate score
    // of the String
    while (s.Count != 0)
    {
 
      // Update ans
      ans += Int32.Parse(s.Peek());
      s.Pop();
    }
    return ans;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String S1 = "(()(()))";
    Console.Write(scoreOfParentheses(S1) +"\n");
  }
}
 
// This code is contributed by 29AjayKumar


输出:
6

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live