首页 > 其他 > 详细

【Leetcode】Edit Distance

时间:2016-05-22 12:23:36      阅读:136      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/problems/edit-distance/
题目:

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

思路:

c[i][j]表示word1的0~i子串和word2的0~j子串的最小编辑距离。状态转移方程:

如果sc[i]==tc[j]即最后一个字符相等 : c[i][j]=min{c[i-1][j],c[i][j-1],c[i-1][j-1]}

否则最后一个字符需要替换增加1个编辑距离:c[i][j]=min{c[i-1][j],c[i][j-1],c[i-1][j-1]+1}

算法

[java] view plain copy
 技术分享技术分享
  1. public int minDistance(String word1, String word2) {  
  2.     char sc[] = word1.toCharArray();  
  3.     char tc[] = word2.toCharArray();  
  4.     int[][] c = new int[word1.length() + 1][word2.length() + 1];  
  5.   
  6.     for (int i = 0; i <= word1.length(); i++) {  
  7.         c[i][0] = i;  
  8.     }  
  9.     for (int j = 0; j <= word2.length(); j++) {  
  10.         c[0][j] = j;  
  11.     }  
  12.   
  13.     for (int i = 1; i <= word1.length(); i++) {  
  14.         for (int j = 1; j <= word2.length(); j++) {  
  15.             int n1 = c[i - 1][j] + 1;  
  16.             int n2 = c[i][j - 1] + 1;  
  17.             int n3 = c[i - 1][j - 1];  
  18.             if (sc[i - 1] != tc[j - 1])  
  19.                 n3++;  
  20.             c[i][j] = Math.min(n1, n2);  
  21.             c[i][j] = Math.min(c[i][j], n3);  
  22.         }  
  23.     }  
  24.     return c[word1.length()][word2.length()];  
  25. }  

【Leetcode】Edit Distance

原文:http://blog.csdn.net/yeqiuzs/article/details/51472695

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!