题解 | #计算字符串的编辑距离#
计算字符串的编辑距离
https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314?tpId=37&tags=&title=&difficulty=&judgeStatus=&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26pageSize%3D100%26search%3D%26tpId%3D37%26type%3D37&gioEnter=menu
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String s1 = in.nextLine(); String s2 = in.nextLine(); System.out.println(Levenshtein(s1, s2)); } in.close(); } /** * dp[i][j] -- 字符串0-i与另一字符串0-j相比的最小编辑距离 * dp[i][j] = min{dp[i-1][j]+1,dp[i-1][j-1]+?,dp[i][j-1]+1} * dp[i-1][j]+1 ---相当于直接把i删了,让i变成i-1和j去比较 * dp[i-1][j-1]+? --- 就是看新加的i和j是否相等,相等的话,?=0,不等的话就是1 * dp[i][j-1]+1 --- dp[i][j-1]知道了,那么只要把j删了,变成[i][j-1]就行了 */ public static int Levenshtein(String s1, String s2) { int[][] dp = new int[s1.length() + 1][s2.length() + 1]; //初始化dp第一列的值 for (int i = 0; i < dp.length; i++) { dp[i][0] = i; } //初始化dp第一行的值 for (int i = 0; i < dp[0].length; i++) { dp[0][i] = i; } for (int i = 1; i < dp.length ; i++) { for (int j = 1; j < dp[0].length; j++) { dp[i][j] = Math.min(dp[i][j - 1] + 1, dp[i - 1][j] + 1); int may = s1.charAt(i - 1) == s2.charAt(j - 1) ? 0 : 1; dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + may); } } return dp[s1.length()][s2.length()]; } }