Minimize length of a string by removing occurrences of another string from it as a substring | C ++ program for the above approach ; Function to minimize length of string S after removing all occurrences of string T as substring ; Count of characters required to be removed ; Iterate over the string ; Insert the current character to temp ; Check if the last M characters forms t or not ; Getting the last M characters . If they are equal to t then remove the last M characters from the temp string ; Incrementing subtract by M ; Removing last M characters from the string ; Print the final answer ; Driver Code ; Given string S & T ; Length of string S ; Length of string T ; Prints the count of operations required
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minLength ( string & S , string & T , int N , int M ) { string temp ; int subtract = 0 ; for ( int i = 0 ; i < N ; ++ i ) { temp . push_back ( S [ i ] ) ; if ( temp . size ( ) >= M ) { if ( temp . substr ( temp . size ( ) - M , M ) == T ) { subtract += M ; int cnt = 0 ; while ( cnt != M ) { temp . pop_back ( ) ; ++ cnt ; } } } } cout << ( N - subtract ) << " STRNEWLINE " ; } int main ( ) { string S = " aabcbcbd " , T = " abc " ; int N = S . size ( ) ; int M = T . size ( ) ; minLength ( S , T , N , M ) ; }