You are given str1=’abc’, str2=’bcd’, Here to make the string equal, we have to delete ‘a’ from str1 and ‘d’ from str2, which will add 97 and 100 to the answer. Hence the answer is 197
The first line of input contains a single integer ‘t’ representing the number of test cases.
The first line of each test case contains a single string representing the string ‘str1.’
The second line of each test case contains a single string representing the string ‘str2.’
For each test case, print a single integer representing the minimum sum of ASCII characters to delete to make both strings equal.
Print a separate line for each test case.
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
1 <= T <= 10
1 <= str1.size(), str2.size() <= 1000
In this approach, we will check every possibility using recursion and get the minimum possible answer. Suppose we are at the ith and jth positions of ‘str1’ and ‘str2’ respectively. There can be only two possibilities.
We create a recursive function, findMaxSum(str1, str2, i, j), where str1 and str2 are the strings we are checking and i and j are the indices of the strings.
We also create tillEndSum(str, index), which returns the ASCII sum from the index to the length of the string.
Algorithm:
In this approach, we will do the same as the previous approach, but this time we will create a cache to store the result of each state in the recursive function so that it does not recalculate each time.
We create a recursive function, findMaxSum(str1, str2, i, j, cache), where str1 and str2 are the strings we are checking and i and j are the indices of the strings. ‘Cache’ is the cache of states.
We also create tillEndSum(str, index), which returns the ASCII sum from the index to the length of the string.
Algorithm:
In this approach, we will try to build a solution with dynamic programming using bottom-up. We will create a dp table where dp[i][j] will represent the minimum ASCII delete sum till the ith and jth index of str1 and str2, respectively.
Therefore from the above two approaches we can conclude that
if str[i] == str[2] dp[i][j] = dp[i - 1][j - 1] if not, d[i][j] is minimum(dp[i - 1][j] + str1[i - 1], dp[i][j - 1] + str2[j - 1]), We use i - 1 and j - 1 as char index to accommodate for 0 length string.
Algorithm: