编辑距离(附带操作)
作者:互联网
package N02;
public class Solution {
class Node{
int value;
//选择
//0表示啥都不做,1表示插入,2表示删除,3表示替换
int choice;
Node(int value, int choice){
this.value = value;
this.choice = choice;
}
}
public int minDistance(String str1, String str2) {
int m = str1.length();
int n = str2.length();
Node[][] dp = new Node[m + 1][n + 1];
//初始化基础情况
for(int i = 0; i <= m; i ++) {
dp[i][0] = new Node(i, 2); //删除
}
for(int j = 1; j <= n; j ++) {
dp[0][j] = new Node(j, 1);
}
for(int i = 1; i <= m; i ++) {
for(int j = 1; j <= n; j ++) {
if(str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = new Node(dp[i - 1][j - 1].value, 0);
}else {
dp[i][j] = minNode(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]);
dp[i][j].value ++;
}
}
}
//展示最后的结果
printResult(dp, str1, str2);
return dp[m][n].value;
}
//a表示删除,b表示替换,c表示添加
private Node minNode(Node a, Node b, Node c) {
Node res = new Node(a.value, 2);
if(res.value > b.value) {
res.value = b.value;
res.choice = 3;
}
if(res.value > c.value) {
res.value = c.value;
res.choice = 1;
}
return res;
}
//展示最后的结果
//这里的dp表示的是操作,str1,str2表示的是数据
private void printResult(Node[][] dp, String str1, String str2) {
int rows = dp.length;
int cols = dp[0].length;
int i = rows - 1, j = cols - 1;//标识位
System.out.println("从" + str1 + "到" + str2 + "的最短编辑距离为:");
while(i != 0 && j != 0) {
char c1 = str1.charAt(i - 1);
char c2 = str2.charAt(j - 1);
int choice = dp[i][j].choice;
//每次都要打印
System.out.print("s1[" + (i - 1) + "]");
switch(choice) {
case 0:
System.out.println("跳过'" + c1 + "'");
//移动游标
i --;
j --;
break;
case 1:
System.out.println("插入'" + c2 + "'");
j --;
break;
case 2:
System.out.println("删除'" + c1 + "'");
i --;
break;
case 3:
System.out.println("替换'" + c1 + "'" + "为'" + c2 + "'");
i --;
j --;
break;
}
}
while(i > 0) {
System.out.print("s1[" + (i - 1) + "]");
System.out.println("删除'" + str1.charAt(i - 1) + "'");
i --;
}
while(j > 0){
System.out.print("s1[" + (i - 1) + "]");
System.out.println("添加'" + str2.charAt(j - 1) + "'");
j --;
}
}
}
标签:Node,附带,System,value,编辑,int,距离,dp,out 来源: https://blog.csdn.net/qq_44652489/article/details/120623338