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

计算字符串的编辑距离

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]);
    }
}

全部评论

相关推荐

群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务