码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Edit Distance

时间:2015-03-19 09:52:36      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

Still a DP problem.

The transition function is not hard to get:

1. When s[i-1] == t[j-1], which means we dont have to do any thing to handle the current chars. Then dp[i][j] = dp[i-1][j-1].

2. Otherwise, find the minimum then plus 1, since each operation takes one step.

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

 

LeetCode – Refresh – Edit Distance

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4349416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!