leetcode 072 —— Edit Distance

来源:互联网 发布:怀来大数据产业园 编辑:程序博客网 时间:2024/06/04 20:02

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


思路:动态规划,所有的动态规划几乎都可以找到对应的模板,关键是转移方程

class Solution {public:int minDistance(string word1, string word2) {int m = word1.size();int n = word2.size();vector<vector<int>> mat(m+1, vector<int>(n+1, 0));for (int i = 0; i <= m; i++)mat[i][0] = i;for (int i = 0; i <= n; i++)mat[0][i] = i;for (int i = 1; i <= m; i++){for (int j = 1; j <= n; j++){if (word1[i - 1] == word2[j - 1]){mat[i][j] = mat[i - 1][j - 1];}else{mat[i][j] = min(mat[i - 1][j - 1],min( mat[i - 1][j], mat[i][j - 1])) + 1;}}}return mat[m][n];}};


0 0
原创粉丝点击