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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicates ( string str ) { int n = str . length ( ) ; unordered_set < char > s ; string res = " " ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s . find ( str [ i ] ) == s . end ( ) ) { res = res + str [ i ] ; s . insert ( str [ i ] ) ; } } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << removeDuplicates ( str ) ; return 0 ; }