zoukankan      html  css  js  c++  java
  • 72. Edit Distance

    一、题目

      1、审题

      2、分析

        给出两个单词字符串,word1 经过字符的删除、替换、插入,最少需要几步才能变为 word2.

    二、解答

      1、思路:

        f(i, j) 代表 word1 的前 i 个字符与 word2 的前 j 个字符的最小代价:

        ①、若 word1[i] == word2[j],则 f(i, j) = f(i-1, j-1).

        ②、若 word1[i] != word2[j],则 f(i, j) = 1 + Min(f(i-1, j) ,  f(i, j-1),  f(i-1, j-1) );

          其中 f(i-1, j), 代表word1删除第 i 个字符;

          f(i, j-1) 代表 word1 插入一个字符;

          f(i-1, j-1) 代表 word1 替换第 i 个字符

     

    public int minDistance(String word1, String word2) {
            
            int m = word1.length();
            int n = word2.length();
            
            int[][] cost = new int[m+1][n+1]; // 代价
            for (int i = 0; i < m; i++)     // 
                cost[i][0] = i;     // word1 的前 i 个字符 删除操作
            
            for (int i = 0; i < n; i++) 
                cost[0][i] = i;
            
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if(word1.charAt(i) == word2.charAt(j))
                        cost[i+1][j+1] = cost[i][j];
                    else {
                        int a = cost[i][j];
                        int b = cost[i][j+1];
                        int c = cost[i+1][j];
                        
                        // 找最小代价
                        cost[i+1][j+1] = 1 + Math.min(Math.min(a, b), c);
                    }
                }
            }
            return cost[m][n];
        }

      

      2、答案链接:

        https://leetcode.com/problems/edit-distance/discuss/25849/Java-DP-solution-O(nm)

  • 相关阅读:
    第十一章关联容器
    第十章泛型算法
    第九章
    第八章
    阅读记录
    java.lang.Class阅读笔记
    java.time包阅读笔记
    CLion运行多个main函数
    c++中lower_bound和upper_bound中的comp参数
    如何写dfs
  • 原文地址:https://www.cnblogs.com/skillking/p/9687281.html
Copyright © 2011-2022 走看看