Remove duplicates from string keeping the order according to last occurrences | C # 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
using System ; using System . Collections . Generic ; class GFG { static String removeDuplicates ( String str ) { int n = str . Length ; HashSet < char > s = new HashSet < char > ( ) ; String res = " " ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! s . Contains ( str [ i ] ) ) { res = res + str [ i ] ; s . Add ( str [ 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 . Join ( " " , a ) ; } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; Console . Write ( removeDuplicates ( str ) ) ; } }