《算法导论》15-3:编辑距离

来源:互联网 发布:数据库故障应急预案 编辑:程序博客网 时间:2024/05/01 06:40


(1)初始化:

cost[i][0] =deleteCost * i

cost[0][j] =insertCost * i


(2)递推公式:


(3)kill操作


public class EditDistance {private String src;            //源文本串private String dst;   //目标字符串//6种转换操作的代价private int[] opCost;//opCost[0] copy代价//opCost[1] replace代价//opCost[2] delete代价//opCost[3] insert代价//opCost[4] exchange代价//opCost[5] kill代价private int[][] cost;public EditDistance(String src, String dst, int[] opCost){this.src = src;this.dst = dst;this.opCost = opCost;this.cost = new int[src.length() + 1][dst.length() + 1];}public int getMinCost(){int i = 0, j = 0 , k = 0;int[] currentCost = new int[opCost.length - 1];for(i = 0; i <= src.length(); i++){cost[i][0] = i * opCost[2];}for(j = 0; j <= dst.length(); j++){cost[0][j] = j * opCost[3];}for(i = 1 ; i <= src.length(); i++){for(j = 1; j <= dst.length(); j++){for(k = 0; k < opCost.length - 1; k++){currentCost[k] = Integer.MAX_VALUE;}//use copy operationif(src.charAt(i-1) == dst.charAt(j-1)){currentCost[0] = opCost[0] + cost[i - 1][j - 1];}else{//use replace operationcurrentCost[1] = opCost[1] + cost[i - 1][j - 1];//use delete operationcurrentCost[2] = opCost[2] + cost[i - 1][j];//use exchange operationif(i >= 2 && j >= 2 &&    src.charAt(i - 1) == dst.charAt(j - 2) &&    src.charAt(i - 2) == dst.charAt(j - 1)){currentCost[4] = opCost[4] + cost[i - 2][j - 2];}}//use insert operationcurrentCost[3] = opCost[3] + cost[i][j - 1];//choose the min Cost of the 5 operation as the current costcost[i][j] = min(currentCost);}}int minCost = cost[src.length()][dst.length()];for(k = 1; k < src.length(); k++){if(cost[k][src.length()] + opCost[5] < minCost){minCost = cost[k][dst.length()] + opCost[5];}}return minCost;}private int min(int[] array){int minValue = Integer.MAX_VALUE;for(int i = 0; i < array.length; i++){if(array[i] < minValue) minValue = array[i];}return minValue;}public static void main(String[] args){String src = "algorithm";String dst = "altruistic";int[] opCost = {1, 2, 3, 3, 2, 5};EditDistance ED = new EditDistance(src, dst, opCost);System.out.println(ED.getMinCost());}}