
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Balance a String After Removing Extra Brackets in C++
A string is an array of characters. In this problem, we are given a string which has opening and closing brackets. And we will balance this string by removing extra brackets from the string.
Let’s take an example,
Input : “)Tutor)ials(p(oin)t(...)” Output : “Tutorials(p(oin)t(...))”
To solve this problem, we will traverse through the string and check for matching brackets. For unmatched brackets eliminate the closing brackets.
Algorithm
Step 1 : Traverse the string from left to right. Step 2 : For opening bracket ‘(’ , print it and increase the count. Step 3 : For occurence of closing bracket ‘)’ , print it only if count is greater than 0 and decrease the count. Step 4 : Print all characters other than brackets are to be printed in the array. Step 5 : In the last add closing brackets ‘)’ , to make the count 0 by decrementing count with every bracket.
Example
#include<iostream> #include<string.h> using namespace std; void balancedbrackets(string str){ int count = 0, i; int n = str.length(); for (i = 0; i < n; i++) { if (str[i] == '(') { cout << str[i]; count++; } else if (str[i] == ')' && count != 0) { cout << str[i]; count--; } else if (str[i] != ')') cout << str[i]; } if (count != 0) for (i = 0; i < count; i++) cout << ")"; } int main() { string str = ")Tutor)ials(p(oin)t(...)"; cout<<"Original string : "<<str; cout<<"\nBalanced string : "; balancedbrackets(str); return 0; }
Output
Original string : )Tutor)ials(p(oin)t(...) Balanced string : Tutorials(p(oin)t(...))
Advertisements