解题思路
-
状态定义:
dp[i][j]
表示将字符串1的前i个字符转换成字符串2的前j个字符所需的最小操作次数
-
状态转移:
- 如果当前字符相同:
dp[i][j] = dp[i-1][j-1]
- 如果当前字符不同,取三种操作的最小值:
- 插入:
dp[i][j-1] + 1
- 删除:
dp[i-1][j] + 1
- 替换:
dp[i-1][j-1] + 1
- 插入:
- 如果当前字符相同:
-
边界条件:
dp[i][0]
= i(删除i个字符)dp[0][j]
= j(插入j个字符)
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length();
int n = word2.length();
// 创建dp数组
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
// 初始化边界
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(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}
return dp[m][n];
}
};
int main() {
string word1, word2;
cin >> word1 >> word2;
Solution solution;
cout << solution.minDistance(word1, word2) << endl;
return 0;
}
import java.util.*;
public class Main {
static class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
// 创建dp数组
int[][] dp = new int[m + 1][n + 1];
// 初始化边界
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.charAt(i-1) == word2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = Math.min(dp[i-1][j-1],
Math.min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}
return dp[m][n];
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word1 = sc.next();
String word2 = sc.next();
Solution solution = new Solution();
System.out.println(solution.minDistance(word1, word2));
}
}
def min_distance(word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
# 创建dp数组
dp = [[0] * (n + 1) for _ in range(m + 1)]
# 初始化边界
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# 填充dp数组
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
return dp[m][n]
if __name__ == "__main__":
word1 = input()
word2 = input()
print(min_distance(word1, word2))
算法及复杂度
- 算法:动态规划
- 时间复杂度:,其中 和 分别是两个字符串的长度
- 空间复杂度:,用于存储 数组