Minimize a string by removing all occurrences of another string | 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
def minLength ( Str , N , K , M ) : NEW_LINE INDENT stackOfChar = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT stackOfChar . append ( Str [ i ] ) NEW_LINE if ( len ( stackOfChar ) >= M ) : NEW_LINE INDENT l = " " NEW_LINE for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( K [ j ] != stackOfChar [ - 1 ] ) : NEW_LINE INDENT f = 0 NEW_LINE while ( f != len ( l ) ) : NEW_LINE INDENT stackOfChar . append ( l [ f ] ) NEW_LINE f += 1 NEW_LINE DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT l = stackOfChar [ - 1 ] + l NEW_LINE stackOfChar . pop ( ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return len ( stackOfChar ) NEW_LINE DEDENT S1 = " fffoxoxoxfxo " NEW_LINE S2 = " fox " NEW_LINE N = len ( S1 ) NEW_LINE M = len ( S2 ) NEW_LINE print ( minLength ( S1 , N , S2 , M ) ) NEW_LINE