Find the resultant String after replacing X with Y and removing Z | C ++ program to find the resultant String after replacing X with Y and removing Z ; Function to replace and remove ; Two pointer start and end points to beginning and end position in the string ; If start is having Z find X pos in end and replace Z with another character ; Find location for having different character instead of Z ; If found swap character at start and end ; Else increment start Also checkin for X at start position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replaceRemove ( string & s , char X , char Y , char Z ) { int start = 0 , end = s . size ( ) - 1 ; while ( start <= end ) { if ( s [ start ] == Z ) { while ( end >= 0 && s [ end ] == Z ) { end -- ; } if ( end > start ) { swap ( s [ start ] , s [ end ] ) ; if ( s [ start ] == X ) s [ start ] = Y ; start ++ ; } } else { if ( s [ start ] == X ) s [ start ] = Y ; start ++ ; } } while ( s . size ( ) > 0 && s [ s . size ( ) - 1 ] == Z ) { s . pop_back ( ) ; } } int main ( ) { string str = " batman " ; char X = ' a ' , Y = ' d ' , Z = ' b ' ; replaceRemove ( str , X , Y , Z ) ; if ( str . size ( ) == 0 ) { cout << -1 ; } else { cout << str ; } return 0 ; }