LeetCode72 Edit Distance

Posted wangxiaobao的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode72 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: (Hard)

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

分析:

双序列动态规划问题,dp[i][j]表示第一个序列i ...和 第二个序列j ...;

对应本题:

1. 状态: dp[i][j]表示第一个字符串前i个字符到第二个字符串前j个字符需要的编辑距离;
2. 递推关系:
  如果 s1[i] == s2[j]
    dp[i][j] = min(dp[i-1][j-1] //表示修改
           ,dp[i-1][j] + 1 //表示删除
             ,dp[i][j-1] + 1) //表示增加
  如果 s1[i] != s2[j]
    dp[i][j] = min(dp[i-1][j-1] ,dp[i-1][j],dp[i][j-1]) + 1

3. 初始化:

  dp[i][0] = i; i = 1...m;
  dp[0][j] = j; j = 1...n;

代码:

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         //dp[i][j]表示第一个字符串前i个字符到第二个字符串前j个字符需要的编辑距离;
 5         int m = word1.size(), n = word2.size() ;
 6         int length = max(m,n);
 7         int dp[length + 1][length + 1];
 8         dp[0][0] = 0;
 9         for(int i = 1;i <= m;++i){
10             dp[i][0] = i;    
11         }
12         for(int i = 1; i <= n;++i){
13             dp[0][i] = i;
14         }
15         for(int i = 1; i <= m; ++i){
16             for(int j = 1; j <= n; ++j){
17                 if(word1[i - 1] != word2[j - 1]){
18                     dp[i][j] = min( min(dp[i-1][j-1],dp[i-1][j]), dp[i][j-1]) + 1;
19                 }
20                 else{
21                     dp[i][j] = min( min(dp[i-1][j-1], dp[i-1][j] + 1), dp[i][j-1] + 1);
22                 }
23             }
24         }
25         return dp[m][n];    
26     }
27 };

 

 

 

以上是关于LeetCode72 Edit Distance的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-72.Edit Distance

LeetCode-72-Edit Distance

LeetCode72 Edit Distance

leetcode72. Edit Distance

[leetcode72]Edit Distance

Leetcode 72: Edit Distance