Find if an expression has duplicate parenthesis or not | Java 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
import java . util . Stack ; public class GFG { static boolean findDuplicateparenthesis ( String s ) { Stack < Character > Stack = new Stack < > ( ) ; char [ ] str = s . toCharArray ( ) ; for ( char ch : str ) { if ( ch == ' ) ' ) { char top = Stack . peek ( ) ; Stack . pop ( ) ; int elementsInside = 0 ; while ( top != ' ( ' ) { elementsInside ++ ; top = Stack . peek ( ) ; Stack . pop ( ) ; } if ( elementsInside < 1 ) { return true ; } } else { Stack . push ( ch ) ; } } return false ; } public static void main ( String [ ] args ) { String str = " ( ( ( a + ( b ) ) + ( c + d ) ) ) " ; if ( findDuplicateparenthesis ( str ) ) { System . out . println ( " Duplicate ▁ Found ▁ " ) ; } else { System . out . println ( " No ▁ Duplicates ▁ Found ▁ " ) ; } } }