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
function minLength ( str , N , K , M ) { var stackOfChar = [ ] ; for ( var i = 0 ; i < N ; i ++ ) { stackOfChar . push ( str [ i ] ) ; if ( stackOfChar . length >= M ) { var l = " " ; for ( var j = M - 1 ; j >= 0 ; j -- ) { if ( K [ j ] != stackOfChar [ stackOfChar . length - 1 ] ) { var f = 0 ; while ( f != l . length ) { stackOfChar . push ( l [ f ] ) ; f ++ ; } break ; } else { l = stackOfChar [ stackOfChar . length - 1 ] + l ; stackOfChar . pop ( ) ; } } } } return stackOfChar . length ; } var S1 = " " ; var S2 = " " ; var N = S1 . length ; var M = S2 . length ; document . write ( minLength ( S1 , N , S2 , M ) ) ;