Calculate score of a string consisting of balanced parentheses
Last Updated :
02 Sep, 2022
Given a string str consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the following rules:
- “()” has a score of 1.
- “x y” has a score of x + y where x and y are individual pairs of balanced parentheses.
- “(x)” has a score twice of x (i.e), 2 * score of x.
Examples:
Input: str = “()()”
Output: 2
Explanation: There are two individual pairs of balanced parentheses “() ()”. Therefore, score = score of “()” + score of “()” = 1 + 1 = 2
Input: str = “(())”
Output: 2
Explanation: Since the input is of the form “(x)”, the total score = 2 * score of “()” = 2 * 1 = 2
Approach: The problem can be solved using Stack. The idea is to iterate over the characters of the string. For every ith character check if the character is ‘(‘ or not. If found to be true, then insert the character into the stack. Otherwise, calculate the score of the inner parentheses and insert double of the score into the stack. Follow the steps below to solve the problem:
- Initialize a stack to store the current traversed character or the score of inner balanced parentheses.
- Iterate over the characters of the string, str. For every ith character check the following conditions:
- Finally, print the total score obtained.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <stack>
using namespace std;
long long scoreOfParentheses(string S)
{
stack<string> s;
int i = 0;
long long ans = 0;
while (i < S.length()) {
if (S[i] == '(' )
s.push( "(" );
else {
if (s.top() == "(" ) {
s.pop();
s.push( "1" );
}
else {
long long count = 0;
while (s.top() != "(" ) {
count += stoi(s.top());
s.pop();
}
s.pop();
s.push(to_string(2 * count));
}
}
i++;
}
while (!s.empty()) {
ans += stoi(s.top());
s.pop();
}
return ans;
}
int main()
{
string S1 = "(()(()))" ;
cout << scoreOfParentheses(S1) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static long scoreOfParentheses(String S)
{
Stack<String> s = new Stack<>();
int i = 0 ;
long ans = 0 ;
while (i < S.length())
{
if (S.charAt(i) == '(' )
s.add( "(" );
else
{
if (s.peek() == "(" )
{
s.pop();
s.add( "1" );
}
else
{
long count = 0 ;
while (s.peek() != "(" )
{
count += Integer.parseInt(s.peek());
s.pop();
}
s.pop();
s.add(String.valueOf( 2 * count));
}
}
i++;
}
while (!s.isEmpty())
{
ans += Integer.parseInt(s.peek());
s.pop();
}
return ans;
}
public static void main(String[] args)
{
String S1 = "(()(()))" ;
System.out.print(scoreOfParentheses(S1) + "\n" );
}
}
|
Python3
def scoreOfParentheses(S):
s = []
i = 0
ans = 0
while (i < len (S)):
if (S[i] = = '(' ):
s.append( "(" )
else :
if (s[ - 1 ] = = "(" ):
s.pop()
s.append( "1" )
else :
count = 0
while (s[ - 1 ] ! = "(" ):
count + = int (s[ - 1 ])
s.pop()
s.pop()
s.append( str ( 2 * count))
i + = 1
while len (s) > 0 :
ans + = int (s[ - 1 ])
s.pop()
return ans
if __name__ = = '__main__' :
S1 = "(()(()))"
print (scoreOfParentheses(S1))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static long scoreOfParentheses(String S)
{
Stack<String> s = new Stack<String>();
int i = 0;
long ans = 0;
while (i < S.Length)
{
if (S[i] == '(' )
s.Push( "(" );
else
{
if (s.Peek() == "(" )
{
s.Pop();
s.Push( "1" );
}
else
{
long count = 0;
while (s.Peek() != "(" )
{
count += Int32.Parse(s.Peek());
s.Pop();
}
s.Pop();
s.Push(String.Join( "" , 2 * count));
}
}
i++;
}
while (s.Count != 0)
{
ans += Int32.Parse(s.Peek());
s.Pop();
}
return ans;
}
public static void Main(String[] args)
{
String S1 = "(()(()))" ;
Console.Write(scoreOfParentheses(S1) + "\n" );
}
}
|
Javascript
<script>
function scoreOfParentheses(S)
{
var s = [];
var i = 0;
var ans = 0;
while (i < S.length) {
if (S[i] == '(' )
s.push( "(" );
else {
if (s[s.length-1] == "(" ) {
s.pop();
s.push( "1" );
}
else {
var count = 0;
while (s[s.length-1] != "(" ) {
count += parseInt(s[s.length-1]);
s.pop();
}
s.pop();
s.push((2 * count).toString());
}
}
i++;
}
while (s.length!=0) {
ans += parseInt(s[s.length-1]);
s.pop();
}
return ans;
}
var S1 = "(()(()))" ;
document.write( scoreOfParentheses(S1));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...