Minimize length of a string by removing occurrences of another string from it as a substring | Java 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
import java . io . * ; import java . util . * ; class GFG { static void minLength ( String S , String T , int N , int M ) { String temp = " " ; int subtract = 0 ; for ( int i = 0 ; i < N ; ++ i ) { temp += S . charAt ( i ) ; if ( temp . length ( ) >= M ) { if ( T . equals ( temp . substring ( temp . length ( ) - M , temp . length ( ) ) ) ) { subtract += M ; int cnt = 0 ; while ( cnt != M ) { temp = temp . substring ( 0 , temp . length ( ) - 1 ) ; ++ cnt ; } } } } System . out . println ( ( N - subtract ) ) ; } public static void main ( String [ ] args ) { String S = " aabcbcbd " , T = " abc " ; int N = S . length ( ) ; int M = T . length ( ) ; minLength ( S , T , N , M ) ; } }