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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string ShortenString ( string str1 ) { stack < char > st ; int i = 0 ; while ( i < str1 . length ( ) ) { if ( st . empty ( ) || str1 [ i ] != st . top ( ) ) { st . push ( str1 [ i ] ) ; i ++ ; } else { st . pop ( ) ; i ++ ; } } if ( st . empty ( ) ) { return ( " Empty ▁ String " ) ; } else { string short_string = " " ; while ( ! st . empty ( ) ) { short_string = st . top ( ) + short_string ; st . pop ( ) ; } return ( short_string ) ; } } int main ( ) { string str1 = " azzxzy " ; cout << ShortenString ( str1 ) ; return 0 ; }