Find if an expression has duplicate parenthesis or not in C++

C++Server Side ProgrammingProgramming

Consider we have an expression exp, and we have to check whether the exp has a duplicate set of parentheses around it or not. An expression will have duplicate parentheses if one sub-expression will be surrounded by more than one parentheses set. For example, if the expression is like −

(5+((7−3)))

Here the sub-expression (7 – 3) is surrounded by two parentheses pair, so these are duplicate parentheses.

To solve this problem, we will use stacks. We will iterate through each character in the exp, and if the character is opening parentheses ‘(’, or any of the operator or operand, then push it into the stack. When the character is closing parentheses, then repeatedly pop characters from the stack until the matching opening parentheses has found, and a counter is used, whose value will be incremented for every character encountered between opening and closing parentheses pair. Which is equal to the value of the counter, is less than 1, then pair of duplicate parentheses is found, otherwise not found.

Example

 Live Demo

#include<iostream>
#include<stack>
using namespace std;
bool hasDuplicateParentheses(string str) {
   stack<char> stk;
   for (int i = 0; i<str.length(); i++) {
      char ch = str[i];
      if (ch == ')') {
         char top = stk.top();
         stk.pop();
         int count = 0;
         while (top != '(') {
            count++;
            top = stk.top();
            stk.pop();
         }
         if(count < 1) {
            return true;
         }
      }
      else
         stk.push(ch);
   }
   return false;
}
int main() {
   string str = "(5+((7-3)))";
   if (hasDuplicateParentheses(str))
      cout << "Duplicate parentheses has Found";
   else
      cout << "No Duplicates parentheses has Found ";
}

Output

Duplicate parentheses has Found
raja
Published on 19-Dec-2019 12:36:39
Advertisements