You are given two strings, ‘str1’ and ‘str2’. Your task is to delete a few characters (possibly 0) from both strings to make the strings equal. The characters you delete must have the minimum possible sum of their ASCII values.
For Example: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.’
Output Format:
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.
Note:
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
2
abc
bcd
aaab
aaa
197
98
For the first test case, 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.
For the second test case, str1=’aaab’, str2=’aaa’, Here to make the string equal, we can only delete one character ‘b’ from str2, which has an ASCII value of 98. Hence the answer is 98.
2
aaa
bbb
aa
aa
585
0
Try to solve it recursively.
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:
O(N * (M ^ N)), Where ‘N’ and ‘M’ are the lengths of the strings given.
For each possible indices of both strings, we can have M ^ N possible states. There will be a total of N*(M ^ N) states. Hence the final time complexity is O(N*(M ^ N)).
O(max(N, M)), Where N and M are the lengths of the strings given.
The space complexity of the recursion stack will be as much as the length of the largest of the two given strings.