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)

  • 相关阅读:
    js 获取服务端时间,并实现时钟
    微信分享问题记录
    format
    vue-cli3 使用mint-ui
    vue.js 使用记录(1)
    iview admin 生成环境打包时路径问题
    java8:(Lambda 表达式简介)
    SpringBoot: 18.使用Scheduled 定时任务器(转)
    SpringBoot: 16.整合junit单元测试(转)
    SpringBoot: 17.热部署配置(转)
  • 原文地址:https://www.cnblogs.com/skillking/p/9687281.html
Copyright © 2011-2022 走看看