Minimize a string by removing all occurrences of another string | C ++ program for the above approach ; Function to find the minimum length to which string str can be reduced to by removing all occurrences of string K ; Initialize stack of characters ; Push character into the stack ; If stack size >= K . size ( ) ; Create empty string to store characters of stack ; Traverse the string K in reverse ; If any of the characters differ , it means that K is not present in the stack ; Push the elements back into the stack ; Store the string ; Remove top element ; Size of stack gives the minimized length of str ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string str , int N , string K , int M ) { stack < char > stackOfChar ; for ( int i = 0 ; i < N ; i ++ ) { stackOfChar . push ( str [ i ] ) ; if ( stackOfChar . size ( ) >= M ) { string l = " " ; for ( int j = M - 1 ; j >= 0 ; j -- ) { if ( K [ j ] != stackOfChar . top ( ) ) { int f = 0 ; while ( f != l . size ( ) ) { stackOfChar . push ( l [ f ] ) ; f ++ ; } break ; } else { l = stackOfChar . top ( ) + l ; stackOfChar . pop ( ) ; } } } } return stackOfChar . size ( ) ; } int main ( ) { string S1 = " fffoxoxoxfxo " ; string S2 = " fox " ; int N = S1 . length ( ) ; int M = S2 . length ( ) ; cout << minLength ( S1 , N , S2 , M ) ; return 0 ; }