Title Description:
For different strings, we hope to have a way to judge the similarity. We define a set of operation methods to make two different strings the same. The specific operation methods are as follows:
1. Modify a character, such as replacing "a" with "b".
2. Add a character, for example, change "abdd" to "aebdd".
3. Delete a character, such as changing "traveling" to "traveling".
For example, for the two strings "abcdef g" and "abcdef", we think that we can achieve the goal by increasing and decreasing a "g". The above two schemes only need one operation. The number of times needed for this operation is defined as the distance between two strings, and the similarity is equal to the reciprocal of "distance + 1". In other words, the distance between "abcdefg" and "abcdef" is 1, and the similarity is 1 / 2 = 0.5
Given any two strings, can you write an algorithm to calculate their similarity?
Java implementation:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ String strA = in.next(); String strB = in.next(); int ic = 1; int dc = 1; int rc = 1; int cost = strEditCost(strA, strB, ic, dc, rc); System.out.println("1/"+ (cost+1)); } in.close(); } public static int strEditCost(String strA, String strB, int ic, int dc, int rc){ int m = strA.length(); int n = strB.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= n; i++) dp[0][i] = i*ic; for (int i = 1; i <= m; i++) dp[i][0] = i*dc; for (int x = 1; x <= m; x++) { for (int y = 1; y <= n; y++) { int cost1 = dp[x-1][y] + dc; int cost2 = dp[x][y-1] + ic; int cost3 = 0; if(strA.charAt(x-1) == strB.charAt(y-1)) cost3 = dp[x-1][y-1]; else cost3 = dp[x-1][y-1] + rc; dp[x][y] = Math.min(cost1, cost2); dp[x][y] = Math.min(dp[x][y], cost3); } } return dp[m][n]; } }
Knowledge points:
- It is similar to [051] in calculating the distance between two strings. Note that the output is in fractional form rather than decimal form