Sort a string according to the order defined by another string | Java 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 stor 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
class GFG { static int MAX_CHAR = 26 ; static void sortByPattern ( char [ ] str , char [ ] pat ) { int count [ ] = new int [ MAX_CHAR ] ; 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 ] ; } } } public static void main ( String args [ ] ) { char [ ] pat = " bca " . toCharArray ( ) ; char [ ] str = " abc " . toCharArray ( ) ; sortByPattern ( str , pat ) ; System . out . println ( String . valueOf ( str ) ) ; } }