Generate a String from given Strings P and Q based on the given conditions | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void manipulateStrings ( string P , string Q ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < P . size ( ) ; i ++ ) { freq [ P [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { freq [ Q [ i ] - ' a ' ] -- ; } string sb = " " ; int pos = Q [ 0 ] - ' a ' ; for ( int i = 0 ; i <= pos ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb += c ; freq [ i ] -- ; } } sb += Q ; for ( int i = pos + 1 ; i < 26 ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb += c ; freq [ i ] -- ; } } cout << sb << endl ; } int main ( ) { string P = " geeksforgeeksfor " ; string Q = " for " ; manipulateStrings ( P , Q ) ; }