题解 | #计算字符串的编辑距离#
计算字符串的编辑距离
https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314
import java.util.Arrays; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String a = in.nextLine(); String b = in.nextLine(); int out = 0; int[][] table = new int[a.length()+1][b.length()+1]; for (int f=0;f<=b.length();f++){table[0][f]=f;} for (int c=0;c<=a.length();c++){table[c][0]=c;} for (int i=1;i<=a.length();i++){ char ti = a.charAt(i-1); for (int j=1;j<=b.length();j++){ char tj = b.charAt(j-1); if (ti==tj){ table[i][j]=table[i-1][j-1]; }else if (ti!=tj){ int[] l = new int[]{table[i-1][j]+1,table[i][j-1]+1,table[i-1][j-1]+1}; table[i][j]= Arrays.stream(l).min().getAsInt(); } } } int l = table[a.length()][b.length()]; System.out.println(l); } } }