
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Score of Parentheses in C++
Suppose we have a balanced parentheses string S, we have to compute the score of the string based on the following rule −
- The () has score 1
- AB has score A + B, where A and B are two balanced parentheses strings.
- (A) has score 2 * A, where A is a balanced parentheses string.
So if the input is like “(()(()))”, then the output will be 6.
To solve this, we will follow these steps −
- ans := 0, define a stack st
- for i in range 0 to size of string S
- if S[i] is opening parentheses, then insert -1 into stack
- otherwise
- if top of stack is -1, then delete from stack and insert 1 into stack
- otherwise
- x := 0
- while top of stack is not -1
- increase x by st, delete from st
- x := x * 2
- delete from st, and insert x
- while stack is not empty
- increase ans by top of st, and delete top element
- return ans.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int scoreOfParentheses(string S) { int ans = 0; stack <int> st; for(int i = 0; i < S.size(); i+=1){ if(S[i] == '('){ st.push(-1); }else{ if(st.top() == -1){ st.pop(); st.push(1); }else{ int x = 0; while(st.top() != -1){ x += st.top(); st.pop(); } x *= 2; st.pop(); st.push(x); } } } while(!st.empty()){ ans += st.top(); st.pop(); } return ans; } }; main(){ Solution ob; cout << (ob.scoreOfParentheses("(()(()))")); }
Input
"(()(()))"
Output
6
- Related Articles
- Count pairs of parentheses sequences such that parentheses are balanced in C++
- Valid Parentheses in C++
- Remove Invalid Parentheses in C++
- Print all combinations of balanced parentheses in C++
- Reverse Substrings Between Each Pair of Parentheses in C++
- Minimum Score Triangulation of Polygon in C++
- Cost to Balance the parentheses in C++
- Different Ways to Add Parentheses in C++
- Number of Paths with Max Score in C++
- Minimum Remove to Make Valid Parentheses in C++
- Check for balanced parentheses in an expression in C++
- Score After Flipping Matrix in C++
- C++ Remove Invalid Parentheses from an Expression
- Generate Parentheses in Python
- Checking the validity of parentheses in JavaScript

Advertisements