《算法导论》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());}}
- 算法导论-15-3-编辑距离
- 《算法导论》15-3:编辑距离
- 算法导论 15-3 编辑距离
- 算法导论 思考题 15-5a (编辑距离)
- POJ 3356 AGTC(算法导论15-5编辑距离) 经典dp
- 编辑距离与编辑算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离及编辑距离算法
- 编辑距离算法-java
- 编辑距离算法
- 如何使用git为开源社区贡献力量
- Windows网络编程基本概念
- switch
- 用opengl画一个棋盘格,复制和缩放
- Android 4.0 ICS SystemUI浅析——StatusBar加载流程之Notification
- 《算法导论》15-3:编辑距离
- Android 4.0 ICS SystemUI浅析——StatusBar工作流程之时间日期设置
- 揭开Html 标签的面纱,忘不了的html .
- oracle计算表要使用的空间的大小
- Android入门一
- 设置MFC背景颜色
- 交叉编译qt-everywhere-4.8.4
- Java语言深入学习之Java调用C/C++的过程
- 为什么程序原这么苦逼