Balance a string after removing extra brackets in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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(...))
raja
Published on 24-Oct-2019 10:56:41
Advertisements