Remove duplicates from string keeping the order according to last occurrences | Java program to remove duplicate character from character array and print in sorted order ; Used as index in the modified String ; Create an empty hash table ; Traverse through all characters from right to left ; If current character is not in ; Reverse the result String ; Driver code
import java . util . * ; class GFG { static String removeDuplicates ( String str ) { int n = str . length ( ) ; HashSet < Character > s = new HashSet < Character > ( ) ; String res = " " ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! s . contains ( str . charAt ( i ) ) ) { res = res + str . charAt ( i ) ; s . add ( str . charAt ( i ) ) ; } } res = reverse ( res ) ; return res ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . print ( removeDuplicates ( str ) ) ; } }