Shortest string possible after removal of all pairs of similar adjacent characters | Java 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static String removeAdjacent ( String s ) { if ( s . length ( ) == 1 ) return s ; StringBuilder sb = new StringBuilder ( " " ) ; for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) { char c = s . charAt ( i ) ; char d = s . charAt ( i + 1 ) ; if ( c != d ) { sb . append ( c ) ; if ( i == s . length ( ) - 2 ) { sb . append ( d ) ; } } else { for ( int j = i + 2 ; j < s . length ( ) ; j ++ ) sb . append ( s . charAt ( j ) ) ; return sb . toString ( ) ; } } return sb . toString ( ) ; } public static void reduceString ( String s ) { String result = " " ; String pre = s ; while ( true ) { result = removeAdjacent ( pre ) ; if ( result . equals ( pre ) ) break ; pre = result ; } if ( result . length ( ) != 0 ) System . out . println ( result ) ; else System . out . println ( " Empty ▁ String " ) ; } public static void main ( String [ ] args ) { String S = " aaabccddd " ; reduceString ( S ) ; } }