Remove all duplicate adjacent characters from a string using Stack | Java program to implement the above approach ; Function to remove adjacent duplicate elements ; Store the String without duplicate elements ; Store the index of str ; Traverse the String str ; Checks if stack is empty or top of the stack is not equal to current character ; If top element of the stack is equal to the current character ; If stack is empty ; If stack is not Empty ; Driver Code
import java . util . * ; class GFG { static String ShortenString ( String str1 ) { Stack < Character > st = new Stack < Character > ( ) ; int i = 0 ; while ( i < str1 . length ( ) ) { if ( st . isEmpty ( ) || str1 . charAt ( i ) != st . peek ( ) ) { st . add ( str1 . charAt ( i ) ) ; i ++ ; } else { st . pop ( ) ; i ++ ; } } if ( st . isEmpty ( ) ) { return ( " Empty ▁ String " ) ; } else { String short_String = " " ; while ( ! st . isEmpty ( ) ) { short_String = st . peek ( ) + short_String ; st . pop ( ) ; } return ( short_String ) ; } } public static void main ( String [ ] args ) { String str1 = " azzxzy " ; System . out . print ( ShortenString ( str1 ) ) ; } }