题解 | #计算字符串的编辑距离#

计算字符串的编辑距离

https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        String s1 = in.nextLine();
        String s2 = in.nextLine();

        char[] cs1 = s1.toCharArray();
        int cs1Len = cs1.length;
        char[] cs2 = s2.toCharArray();
        int cs2Len = cs2.length;
        int[][] dp = new int[cs1Len + 1][cs2Len + 1];
        dp[0][0] = 0;
        for (int i = 1; i <= cs1Len; i++) {
            dp[i][0] = i;
        }
        for (int i = 1; i <= cs2Len; i++) {
            dp[0][i] = i;
        }

        for (int i = 1; i <= cs1Len; i++) {
            for (int j = 1; j <= cs2Len; j++) {
                if (cs1[i - 1] == cs2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                }
            }
        }
        System.out.print(dp[cs1Len][cs2Len]);
    }
}

全部评论

相关推荐

09-01 16:46
已编辑
门头沟学院 Java
mmvvpp:错了!!给了offer之后还有试用期,试用期过了就完事了?错了!还有每个季度的kpi考核,拿一个c就等着被劝退。那我好好干不拿c不就完了?错了!最多三年劳动合同到期,续不续期未知数。每年都有1800w毕业生毕业,今年你是小萌新蜜月期,明年你是老油条,长江后浪推前浪,前浪死在沙滩上。这就是——互联网!
秋招的破防瞬间
点赞 评论 收藏
分享
08-30 15:51
已编辑
蚌埠坦克学院 Java
狸猫换offer:感觉hr写这段字的时候充满怨气
lastday知无不言
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务