Generate a String from given Strings P and Q based on the given conditions | Java Program to implement the above approach ; Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string ; Index in freq [ ] to segregate the string ; Add Q to the resulting string ; Driver Code ; Function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { public static void manipulateStrings ( String P , String Q ) { int [ ] freq = new int [ 26 ] ; for ( int i = 0 ; i < P . length ( ) ; i ++ ) { freq [ P . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < Q . length ( ) ; i ++ ) { freq [ Q . charAt ( i ) - ' a ' ] -- ; } StringBuilder sb = new StringBuilder ( ) ; int pos = Q . charAt ( 0 ) - ' a ' ; for ( int i = 0 ; i <= pos ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb . append ( c ) ; freq [ i ] -- ; } } sb . append ( Q ) ; for ( int i = pos + 1 ; i < 26 ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb . append ( c ) ; freq [ i ] -- ; } } System . out . println ( sb ) ; } public static void main ( String [ ] args ) { String P = " geeksforgeeksfor " ; String Q = " for " ; manipulateStrings ( P , Q ) ; } }