Expression contains redundant bracket or not | C ++ Program to check whether valid expression is redundant or not ; Function to check redundant brackets in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; If immediate pop have open parenthesis ' ( ' duplicate brackets found ; Check for operators in expression ; Fetch top element of stack ; If operators not found ; push open parenthesis ' ( ' , ; operators and operands to stack ; Function to check redundant brackets ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkRedundancy ( string & str ) { stack < char > st ; for ( auto & ch : str ) { if ( ch == ' ) ' ) { char top = st . top ( ) ; st . pop ( ) ; bool flag = true ; while ( ! st . empty ( ) and top != ' ( ' ) { if ( top == ' + ' top == ' - ' top == ' * ' top == ' / ' ) flag = false ; top = st . top ( ) ; st . pop ( ) ; } if ( flag == true ) return true ; } else st . push ( ch ) ; } return false ; } void findRedundant ( string & str ) { bool ans = checkRedundancy ( str ) ; if ( ans == true ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { string str = " ( ( a + b ) ) " ; findRedundant ( str ) ; str = " ( a + ( b ) / c ) " ; findRedundant ( str ) ; str = " ( a + b * ( c - d ) ) " ; findRedundant ( str ) ; return 0 ; }