Sort a string according to the order defined by another string | C ++ program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array store count of characters in str . ; Count number of occurrences of each character in str . ; Traverse the pattern and print every characters same number of times as it appears in str . This loop takes O ( m + n ) time where m is length of pattern and n is length of str . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void sortByPattern ( string & str , string pat ) { int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) count [ str [ i ] - ' a ' ] ++ ; int index = 0 ; for ( int i = 0 ; i < pat . length ( ) ; i ++ ) for ( int j = 0 ; j < count [ pat [ i ] - ' a ' ] ; j ++ ) str [ index ++ ] = pat [ i ] ; } int main ( ) { string pat = " bca " ; string str = " abc " ; sortByPattern ( str , pat ) ; cout << str ; return 0 ; }