Remove first adjacent pairs of similar characters until possible | Java implementation of the above approach ; Function to remove adjacent duplicates ; Iterate for every character in the string ; If ans string is empty or its last character does not match with the current character then append this character to the string ; Matches with the previous one ; Return the answer ; Driver Code
class GFG { static String removeDuplicates ( String S ) { String ans = " " ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( ans . isEmpty ( ) || ans . charAt ( ans . length ( ) - 1 ) != S . charAt ( i ) ) ans += S . charAt ( i ) ; else if ( ans . charAt ( ans . length ( ) - 1 ) == S . charAt ( i ) ) ans = ans . substring ( 0 , ans . length ( ) - 1 ) ; } return ans ; } public static void main ( String [ ] args ) { String str = " keexxllx " ; System . out . println ( removeDuplicates ( str ) ) ; } }