博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Edit Distance 解答
阅读量:5251 次
发布时间:2019-06-14

本文共 1934 字,大约阅读时间需要 6 分钟。

Question

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:

  • Insert a character
  • Delete a character
  • Replace a character

For example, given word1 = "mart" and word2 = "karma", return 3.

Solution

DP 四要素:1. State 2. Function 3. Initialization 4. Answer

令dp[i][j]表示长度为i的word1和长度为j的word2的最小距离。假设末位分别为x和y。那么根据x和y是否相同,考虑情况如下:

1. x == y

dp[i][j] = dp[i-1][j-1]

2. x != y

a) Delete x => dp[i-1][j] + 1

b) Insert y => dp[i][j-1] + 1

c) Replace x with y => dp[i-1][j-1] + 1

dp[i][j]取a,b,c中最小值。

public class Solution {    /**     * @param word1 & word2: Two string.     * @return: The minimum number of steps.     */    public int minDistance(String word1, String word2) {        // write your code here        int len1 = word1.length();        int len2 = word2.length();        // dp[i][j] represents min distance for word1[0, i - 1] and word2[0, j - 1]        int[][] dp = new int[len1 + 1][len2 + 1];        for (int i = 0; i <= len1; i++) {            dp[i][0] = i;        }        for (int j = 0; j <= len2; j++) {            dp[0][j] = j;        }        for (int i = 1; i <= len1; i++) {            for (int j = 1; j <= len2; j++) {                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {                    dp[i][j] = dp[i - 1][j - 1];                } else {                    // delete word1[i - 1]                    int x = dp[i - 1][j] + 1;                    // insert word2[j - 1] into word1                    int y = dp[i][j - 1] + 1;                    // replace word1[i - 1] with word2[j - 1]                    int z = dp[i - 1][j - 1] + 1;                    dp[i][j] = Math.min(x, y);                    dp[i][j] = Math.min(dp[i][j], z);                }            }        }        return dp[len1][len2];    }}

 

转载于:https://www.cnblogs.com/ireneyanglan/p/5980439.html

你可能感兴趣的文章
tomcat 配置JNDI数据源
查看>>
oracle分页查询
查看>>
Chrome developer tool:本人钟爱的 console、Network 功能简谈
查看>>
DemoKit编译过程
查看>>
请问 imgbtn上怎样添加文字呢
查看>>
golang print struct with key
查看>>
正则表达式判断手机号是否11位数字
查看>>
SAP SUP (转)
查看>>
数组指针和指针数组
查看>>
JedisService的编写
查看>>
Qt程序发布
查看>>
phpcms常用函数
查看>>
linux shell脚本基础知识
查看>>
SUSE Linux忘记root密码的对策
查看>>
HTML,CSS,JS优化
查看>>
request,reponse对象中的方法
查看>>
文法点评名单
查看>>
数据库表添加索引对性能的影响
查看>>
python爬虫基础_requests和bs4
查看>>
C++primer 7.3.3节练习
查看>>