Minimize a string by removing all occurrences of another string | Java 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
import java . util . * ; class GFG { static int minLength ( String str , int N , String K , int M ) { Stack < Character > stackOfChar = new Stack < Character > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { stackOfChar . add ( str . charAt ( i ) ) ; if ( stackOfChar . size ( ) >= M ) { String l = " " ; for ( int j = M - 1 ; j >= 0 ; j -- ) { if ( K . charAt ( j ) != stackOfChar . peek ( ) ) { int f = 0 ; while ( f != l . length ( ) ) { stackOfChar . add ( l . charAt ( f ) ) ; f ++ ; } break ; } else { l = stackOfChar . peek ( ) + l ; stackOfChar . pop ( ) ; } } } } return stackOfChar . size ( ) ; } public static void main ( String [ ] args ) { String S1 = " fffoxoxoxfxo " ; String S2 = " fox " ; int N = S1 . length ( ) ; int M = S2 . length ( ) ; System . out . print ( minLength ( S1 , N , S2 , M ) ) ; } }