题目描述
给你两个单词 word1
和 word2
,请你计算出将 word1
转换成 word2
所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
- 插入一个字符
- 删除一个字符
- 替换一个字符
示例1
输入:word1 = "horse", word2 = "ros"输出:3解释:horse -> rorse (将 'h' 替换为 'r')rorse -> rose (删除 'r')rose -> ros (删除 'e')
示例2
输入:word1="intention", word2="execution"输出:5解释:intention->inention (删除't')inention->enention (将'i'替换为'e')enention->exention (将'n'替换为'x')exention->exection (将'n'替换为'c')exection->execution (插入'u')
题解
代码
c++
classSolution { public: intminDistance(stringword1, stringword2) { intn=word1.size(), m=word2.size(); vector<vector<int>>dp(n+1, vector<int>(m+1, INT_MAX)); dp[0][0] =0; for (inti=0; i<m; ++i) dp[0][i+1] =i+1; for (inti=0; i<n; ++i) dp[i+1][0] =i+1; for (inti=0; i<n; ++i) { for (intj=0; j<m; ++j) { if (word1[i] ==word2[j]) { dp[i+1][j+1] =dp[i][j]; continue; } // 插入 dp[i+1][j+1] =min(dp[i+1][j+1], dp[i+1][j]+1); // 删除 dp[i+1][j+1] =min(dp[i+1][j+1], dp[i][j+1]+1); // 替换 dp[i+1][j+1] =min(dp[i+1][j+1], dp[i][j]+1); } } returndp[n][m]; } };
python
classSolution: defminDistance(self, word1: str, word2: str) ->int: n, m=len(word1), len(word2) dp= [[0]*(m+1) for_inrange(n+1)] dp[0] = [iforiinrange(m+1)] foriinrange(n+1): dp[i][0] =iforiinrange(n): forjinrange(m): ifword1[i] ==word2[j]: dp[i+1][j+1] =dp[i][j] continuedp[i+1][j+1] =min(dp[i+1][j], dp[i][j+1], dp[i][j]) +1returndp[n][m]
关注【算法码上来】,每日算法干货马上就来!
参考资料
[1]
LeetCode 72. 编辑距离: https://leetcode-cn.com/problems/edit-distance/
作者简介:godweiyang,知乎同名,华东师范大学计算机系硕士在读,方向自然语言处理与深度学习。喜欢与人分享技术与知识,期待与你的进一步交流~