题解 | #编辑距离(一)#
编辑距离(一)
https://www.nowcoder.com/practice/6a1483b5be1547b1acd7940f867be0da
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str1 string字符串 * @param str2 string字符串 * @return int整型 */ public int editDistance (String str1, String str2) { // write code here int s1 = str1.length(); int s2 = str2.length(); int [] [] result = new int[s1+1][s2 + 1]; for (int i = 1; i < s1 + 1; i++) { result[i][0] = result[i - 1][0] + 1; } for (int i = 1; i < s2 + 1; i++) { result[0][i] = result[0][i-1] + 1; } for(int i=1;i<=s1;i++){ for(int j=1;j<=s2;j++){ if(str1.charAt(i-1)==str2.charAt(j-1)){ result[i][j]=result[i-1][j-1]; }else{ result[i][j]= Math.min(Math.min(result[i-1][j],result[i][j-1]) ,result[i-1][j-1])+1; } } } return result[s1][s2]; } }