Find index of closing bracket for a given opening bracket in an expression in C++


Consider we have an expression with brackets. If the index of one starting bracket is given, we have to find the closing ending bracket of that. So if the expression is like: (25*6+(88-32+(50/10)+20)), and the index of opening bracket is 6, then closing bracket will be at position 23.

Here we will use the stack data-structure to solve this problem. We will traverse the expression from given index, and start pushing the opening brackets, when closing bracket is found, then pop element from stack, when the stack is empty, then return the index.

Example

 Live Demo

#include<iostream>
#include<stack>
using namespace std;
void getEndingBracketIndex(string exp, int index){
   int i;
   if(exp[index]!='('){
      cout << exp << "Closing bracket of parentheses started at " << index << " present at index -1\n";
      return;
   }
   stack <int> stk;
   for(i = index; i < exp.length(); i++){
      if(exp[i] == '(')
         stk.push(exp[i]);
      else if(exp[i] == ')'){
         stk.pop();
         if(stk.empty()){
            cout << exp << ", Closing bracket of parentheses started at " << index << " present at index " << i << "";
            return;
         }
      }
   }
   cout << exp << ", Closing bracket of parentheses started at " << index << " present at index -1";
}
int main() {
   getEndingBracketIndex("(25*6+(88-32+(50/10)+20))", 6);
}

Output

(25*6+(88-32+(50/10)+20)), Closing bracket of parentheses started at 6 present at index 23

Updated on: 18-Dec-2019

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements