Shortest string possible after removal of all pairs of similar adjacent characters | C ++ program for the above approach ; Function to delete pair of adjacent characters which are equal ; Base Case ; Stores the update string ; Traverse the string s ; If two unequal pair of adjacent characters are found ; If two equal pair of adjacent characters are found ; Append the remaining string after removing the pair ; Return the final String ; Function to find the shortest string after repeatedly removing pairs of adjacent characters which are equal ; Stores the resultant String ; Keeps track of previously iterated string ; Update the result after deleting adjacent pair of characters which are similar ; Termination Conditions ; Update pre variable with the value of result ; Case for " Empty ▁ String " ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeAdjacent ( string s ) { if ( s . length ( ) == 1 ) return s ; string sb = " " ; for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) { char c = s [ i ] ; char d = s [ i + 1 ] ; if ( c != d ) { sb = sb + c ; if ( i == s . length ( ) - 2 ) { sb = sb + d ; } } else { for ( int j = i + 2 ; j < s . length ( ) ; j ++ ) sb = sb + s [ j ] ; return sb ; } } return sb ; } void reduceString ( string s ) { string result = " " ; string pre = s ; while ( true ) { result = removeAdjacent ( pre ) ; if ( result == pre ) break ; pre = result ; } if ( result . length ( ) != 0 ) cout << ( result ) << endl ; else cout << " Empty ▁ String " << endl ; } int main ( ) { string S = " aaabccddd " ; reduceString ( S ) ; return 0 ; }