Find if an expression has duplicate parenthesis or not | C ++ program to find duplicate parenthesis in a balanced expression ; Function to find duplicate parenthesis in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; pop character from the stack ; stores the number of characters between a closing and opening parenthesis if this count is less than or equal to 1 then the brackets are redundant else not ; push open parenthesis ' ( ' , operators and operands to stack ; No duplicates found ; Driver code ; input balanced expression
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findDuplicateparenthesis ( string str ) { stack < char > Stack ; for ( char ch : str ) { if ( ch == ' ) ' ) { char top = Stack . top ( ) ; Stack . pop ( ) ; int elementsInside = 0 ; while ( top != ' ( ' ) { elementsInside ++ ; top = Stack . top ( ) ; Stack . pop ( ) ; } if ( elementsInside < 1 ) { return 1 ; } } else Stack . push ( ch ) ; } return false ; } int main ( ) { string str = " ( ( ( a + ( b ) ) + ( c + d ) ) ) " ; if ( findDuplicateparenthesis ( str ) ) cout << " Duplicate ▁ Found ▁ " ; else cout << " No ▁ Duplicates ▁ Found ▁ " ; return 0 ; }