酷代码 AI
菜单
服务商

#include <iostream> #include <cstdlib> #include <string> using namespace std; int minDistance(string word1,string word2) { //在此处写入代码 } 本关任务: 编写一个函数来实现最短编辑距离计算方法。 编辑距离算法被数据科学家广泛应用,是用作机器翻译和语音识别评价标准的基本算法。 给你两个单词word1和word2(均为小写英文单词),请返回将word1转换成 word2所使用的最少操作数(编辑距离)。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 例如: word1 = "horse", word2 = "ros" 编辑距离=3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e')

```cpp #include <iostream> #include <cstdlib> #include <string> #include <vector> using namespace std; int minDistance(string word1, string word2) { int m = word1.length(); int n = word2.length(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); // 初始化第一行和第一列 for (int i = 0; i <= m; i++) { dp[i][0] = i; } for (int j = 0; j <= n; j++) { dp[0][j] = j; } // 填充dp数组 for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + 1); } } } return dp[m][n]; } ``` [2025-11-12 14:55:49 | AI问答 | 311点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多