Length of longest substring to be deleted to make a string equal to another string | Function to print the length of longest substring to be deleted ; Stores the length of string ; Store the position of previous matched character of str1 ; Store the position of first occurrence of str2 in str1 ; Find the position of the first occurrence of str2 ; Store the index of str1 ; If both characters not matched ; Store the length of the longest deleted substring ; Store the position of last occurrence of str2 in str1 ; If both characters not matched ; Update res ; Update res . ; Given string ; Function Call
function longDelSub ( str1 , str2 ) { var N = str1 . length ; var M = str2 . length ; var prev_pos = 0 ; var pos = new Array ( M ) ; for ( let i = 0 ; i < M ; i ++ ) { var index = prev_pos ; while ( index < N && str1 [ index ] != str2 [ i ] ) { index ++ ; } pos [ i ] = index ; prev_pos = index + 1 ; } var res = N - prev_pos ; prev_pos = N - 1 ; for ( let i = M - 1 ; i >= 0 ; i -- ) { var index = prev_pos ; while ( index >= 0 && str1 [ index ] != str2 [ i ] ) { index -- ; } if ( i != 0 ) { res = Math . max ( res , index - pos [ i - 1 ] - 1 ) ; } prev_pos = index - 1 ; } res = Math . max ( res , prev_pos + 1 ) ; return res ; } var str1 = " " ; var str2 = " " ; console . log ( longDelSub ( str1 , str2 ) ) ;