- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements