Remove all duplicate adjacent characters from a string using Stack | C # 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
using System ; using System . Collections . Generic ; class GFG { static String ShortenString ( String str1 ) { Stack < char > st = new Stack < char > ( ) ; int i = 0 ; while ( i < str1 . Length ) { if ( st . Count == 0 || ( st . Count != 0 && str1 [ i ] != st . Peek ( ) ) ) { st . Push ( str1 [ i ] ) ; i ++ ; } else { if ( st . Count != 0 ) st . Pop ( ) ; i ++ ; } } if ( st . Count == 0 ) { return ( " Empty ▁ String " ) ; } else { String short_String = " " ; while ( st . Count != 0 ) { short_String = st . Peek ( ) + short_String ; st . Pop ( ) ; } return ( short_String ) ; } } public static void Main ( String [ ] args ) { String str1 = " azzxzy " ; Console . Write ( ShortenString ( str1 ) ) ; } }