Problem:
For two strings A and B with the same length, the distance is defined as the sum of the character distance at the corresponding position. The distance between two non-space characters is the absolute value of their ASCII code difference. The distance between a space and a space is 0, and the distance between a space and other characters is a fixed value K. Generally, the length of string a and string B is not necessarily the same. The extension of string a is a string generated by inserting a number of space characters in string. In all extensions of string a and string B with the same length, there is a one-to-one shortest extension, which is called the extension distance between string a and string B. For a given string a and B, design an algorithm to calculate its extended distance.
Test data:
Input: cmc snmn 2 (string a, string B, and value K)
Output: 10
Input: cdd snmn 1 (string a, string B, and value K respectively)
Output: 7
Input: CD Ad 1 (string a, string B, and value K)
Output: 2
// I did not do it on the spot.
// Check it back. It turns out to be a dynamic plan.
// Java implements the following:
import static java.lang.Math.abs;import static java.lang.Math.min;public class DPString { public static int MAX_LEN = 2014; public static int work(char str1[], char str2[], int k) { int[][] dp = new int[MAX_LEN][MAX_LEN]; int length1 = str1.length; int length2 = str2.length; dp[0][0] = 0; for (int i = 1; i <= length1; i++) { dp[i][0] = i * k; } for (int i = 1; i <= length2; i++) { dp[0][i] = i * k; } for (int i = 1; i <= length1; i++) { for (int j = 1; j <= length2; j++) { dp[i][j] = min(dp[i - 1][j - 1] + abs(str1[i - 1] - str2[j - 1]), min(dp[i - 1][j], dp[i][j - 1]) + k); } } return dp[length1][length2]; } public static void main(String[] args) { String stra = "cdd"; String strb = "snmn"; int k = 1; System.out.println(work(stra.toCharArray(), strb.toCharArray(), k));// output 7 }}