Stack: Expression contains redundant bracket or not

Problem Statement:

You are given an expression in the form of a string.
You need to check if the string has redundant brackets.

Example

Input: ((a+b))
Output: True

Solution

We will use stack to solve this problem.

If the current character is not a closing parenthesis “)” then push the char into the stack.

If the current char is closing bracket “)”, then check if the top element is opening parenthesis or not.
If it is an opening parenthesis, then the expression has redundant bracket.
else, pop the characters from the stack till matching “(” is found for current “).”

Solution in C++

#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <stack>
#include <vector>
#include <unordered_map> 
#include <list> 

using namespace std;

void check_if_duplicate_brackets_exist(string exp)
{
    if (exp.length() <= 3) {
        return;
    }
 
    stack<char> stack;
 
    for (char c: exp)
    {
        if (c != ')') 
        {
            stack.push(c);
        }
        else 
        {
            if (stack.top() == '(')
            {
                cout << "The expression has duplicate parenthesis.";
                return;
            }
 

            while (stack.top() != '(') {
                stack.pop();
            }
 
            // pop `(`
            stack.pop();
        }
    }
 
    cout << "The expression does not have duplicate parenthesis";
}
 
int main()
{
    string exp = "((x+y))"; 
 
    check_if_duplicate_brackets_exist(exp);
 
    return 0;
}

Output:

The expression has duplicate parenthesis.

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *