Check if a string consisting only of a , b , c can be made empty by removing substring " abc " recursively | Java program for the above approach ; Function to check if the given String S can be made empty ; Stores the characters of the String S ; Traverse the given String ; If the character is c ; If stack size is greater than 2 ; Pop from the stack ; Top two characters in the stack should be ' b ' and ' a ' respectively ; Otherwise , print No ; If character is ' a ' or ' b ' push to stack ; If stack is empty , then print Yes . Otherwise print No ; Driver Code
import java . util . * ; class GFG { static String canMadeEmpty ( String s , int n ) { Stack < Character > St = new Stack < Character > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' c ' ) { if ( St . size ( ) >= 2 ) { char b = St . peek ( ) ; St . pop ( ) ; char a = St . peek ( ) ; St . pop ( ) ; if ( a != ' a ' b != ' b ' ) return " No " ; } else return " No " ; } else St . add ( s . charAt ( i ) ) ; } if ( St . size ( ) == 0 ) { return " Yes " ; } else { return " No " ; } } public static void main ( String [ ] args ) { String S = " aabcbc " ; int N = S . length ( ) ; System . out . print ( canMadeEmpty ( S , N ) ) ; } }