赞
踩
583. 两个字符串的删除操作
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- int m = word1.size();
- int n = word2.size();
- vector<vector<int>> dp(m + 1, vector<int>(n + 1));
-
- for (int i = 1; i <= m; ++i) {
- dp[i][0] = i;
- }
- for (int j = 1; j <= n; ++j) {
- dp[0][j] = j;
- }
- for (int i = 1; i <= m; i++) {
- char c1 = word1[i - 1];
- for (int j = 1; j <= n; j++) {
- char c2 = word2[j - 1];
- if (c1 == c2) {
- dp[i][j] = dp[i - 1][j - 1];
- } else {
- dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;
- }
- }
- }
-
- return dp[m][n];
- }
- };
java版:
- class Solution {
- public int minDistance(String word1, String word2) {
- int m = word1.length(), n = word2.length();
- int[][] dp = new int[m + 1][n + 1];
- for (int i = 1; i <= m; i++) {
- char c1 = word1.charAt(i - 1);
- for (int j = 1; j <= n; j++) {
- char c2 = word2.charAt(j - 1);
- if (c1 == c2) {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- } else {
- dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
- }
- }
- }
- int lcs = dp[m][n];
- return m - lcs + n - lcs;
- }
- }
72. 编辑距离
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- int n = word1.length();
- int m = word2.length();
-
- if (n * m == 0) return n + m;
-
- vector<vector<int>> D(n + 1, vector<int>(m + 1));
-
- for (int i = 0; i < n + 1; i++) {
- D[i][0] = i;
- }
- for (int j = 0; j < m + 1; j++) {
- D[0][j] = j;
- }
-
- for (int i = 1; i < n + 1; i++) {
- for (int j = 1; j < m + 1; j++) {
- int left = D[i - 1][j] + 1;
- int down = D[i][j - 1] + 1;
- int left_down = D[i - 1][j - 1];
- if (word1[i - 1] != word2[j - 1]) left_down += 1;
- D[i][j] = min(left, min(down, left_down));
-
- }
- }
- return D[n][m];
- }
- };
java版:
- class Solution {
- public int minDistance(String word1, String word2) {
- int n = word1.length();
- int m = word2.length();
-
- // 有一个字符串为空串
- if (n * m == 0) {
- return n + m;
- }
-
- // DP 数组
- int[][] D = new int[n + 1][m + 1];
-
- // 边界状态初始化
- for (int i = 0; i < n + 1; i++) {
- D[i][0] = i;
- }
- for (int j = 0; j < m + 1; j++) {
- D[0][j] = j;
- }
-
- // 计算所有 DP 值
- for (int i = 1; i < n + 1; i++) {
- for (int j = 1; j < m + 1; j++) {
- int left = D[i - 1][j] + 1;
- int down = D[i][j - 1] + 1;
- int left_down = D[i - 1][j - 1];
- if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
- left_down += 1;
- }
- D[i][j] = Math.min(left, Math.min(down, left_down));
- }
- }
- return D[n][m];
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。