Expression contains redundant bracket or not | Java 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
import java . util . Stack ; public class GFG { static boolean checkRedundancy ( String s ) { Stack < Character > st = new Stack < > ( ) ; char [ ] str = s . toCharArray ( ) ; for ( char ch : str ) { if ( ch == ' ) ' ) { char top = st . peek ( ) ; st . pop ( ) ; boolean flag = true ; while ( top != ' ( ' ) { if ( top == ' + ' top == ' - ' top == ' * ' top == ' / ' ) { flag = false ; } top = st . peek ( ) ; st . pop ( ) ; } if ( flag == true ) { return true ; } } else { st . push ( ch ) ; } } return false ; } static void findRedundant ( String str ) { boolean ans = checkRedundancy ( str ) ; if ( ans == true ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { String str = " ( ( a + b ) ) " ; findRedundant ( str ) ; str = " ( a + ( b ) / c ) " ; findRedundant ( str ) ; str = " ( a + b * ( c - d ) ) " ; findRedundant ( str ) ; } }