首页 > 代码库 > leetcode72. Edit Distance

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:

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

给定任意两个字符串,要求只能用删除,替换,添加操作,将word1转变成word2,求最少操作次数。

声明dp[i][j],表示长度为i的字符串word1和长度为j的字符串word2匹配所需要的最小次数。

dp[i][j]有三种迭代可能:

1:dp[i][j] = dp[i-1][j] +1//1表示i多出了一个长度,需要删除。

2:dp[i][j] = dp[i][j-1]+1;//1表示i和j-1匹配的情况下,j多一个字符,需要添加这一步操作。

3:dp[i][j] = dp[i-1][j-1]+(word1[i-1]==word(j-1)?0:1);//表明在各自基础上添加一个字符,若相等则不操作,若不相等。则添加1步替换。

dp[i][j]=min(1,2,3);

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         int m = word1.length();
 5         int n = word2.length();
 6         vector<vector<int> >dp(m+1,vector<int>(n+1));
 7         for(int i = 0; i <= m ;i++){
 8             for(int j = 0 ;j <= n ;j++){
 9                 if(i == 0){
10                     dp[i][j] = j;
11                 }
12                 else if(j==0){
13                     dp[i][j] = i;
14                 }
15                 else{
16                     dp[i][j] = min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+(word1[i-1]==word2[j-1]?0:1)));
17                 }
18             }
19         }
20         return dp[m][n];
21     }
22 };

 

leetcode72. Edit Distance