Print Bracket Number in C++


In this problem, we are given expression. And we have to print the bracket number sequence. Let’s look at an example to understand the problem better.

Example,

Input : ((()())())
Output : 1233442551

Explanation − Here we have encountered 5 bracket pairs and we have printed them in a sequence of their[ occurrence.

Now since we know about the problem, let’s create a solution to this solution.

The solution to this problem requires a stack data structure. We will use one variable that keeps the count of the number of left brackets and stack keeps track of right brackets. We will count left brackets and push them into the stack and pop when the right bracket is encountered.

Algorithm

Step 1 : Initialise leftBrackets = 1. stack rightBrackets, empty.
Step 2 : traverse the expression using variable i = 0 to n-1.
Step 3 : if expression[i] == ‘(’ i.e. left bracket is encountered. Then,
   Step 3.1 : PRINT ‘leftBracket ‘.
   Step 3.2 : push the value of leftBracket in stack.
   Step 3.3 : leftBracket++.
Step 4 : if expression[i] == ‘)’ i.e. right bracket is encountered. Then,
   Step 4.1 : PRINT top of stack.
   Step 4.2 : pop top element of the stack.
Step 5 : EXIT.

Example

Now let’s create programming to illustrate the implementation of the above algorithm.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void bracketCount(string expression, int n){
   int leftBracket = 1;
   stack<int> rightBracket;
   for (int i = 0; i < n; i++) {
      if (expression[i] == '(') {
         cout<<leftBracket<<" ";
         rightBracket.push(leftBracket);
         leftBracket++;
      }
      else if(expression[i] == ')') {
         cout<<rightBracket.top() << " ";
         rightBracket.pop();
      }
   }
}
int main(){
   string expression = "()((())()())";
   int n = expression.size();
   bracketCount(expression, n);
   return 0;
}

Output

1 1 2 3 4 4 3 5 5 6 6 2

Updated on: 03-Jan-2020

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements