[Acwing Algorithm Fundamentals] AcWing 902. Shortest Edit Distance (Dynamic Programming)

Category: Dynamic Programming

insert image description here

topic

Given two strings A and B, now we need to make A into B through some operations

, the possible operations are:

删除–将字符串 A

delete a character in . Insert – Insert a certain character at a certain position
in string A. replace – replace string A

中的某个字符替换为另一个字符。

Now please ask, change A
into B

How many operations are required at least.
input format

The first line contains the integer n
, representing the string A

length.


The second line contains a string A of length n

The third line contains the integer m
, representing the string B

length.


The fourth line contains a string B of length m

Strings contain only uppercase letters.
output format

Output an integer representing the minimum number of operations.
data range

1≤n,m≤1000

Input sample:

10
AGTCTGACGC
11
AGTAAGTAGGC

Sample output:

4

java code

import java.util.Scanner;

public class Main {
    
    
    static Scanner sc = new Scanner(System.in);
    
    static int N = 1010;
    static int f[][] = new int[N][N];
    static char a[] = new char[N];
    static char b[] = new char[N];
    
    public static void main(String[] args) {
    
    
        int n = sc.nextInt();
        sc.nextLine();
        char arr[] = sc.nextLine().toCharArray();

        int m = sc.nextInt();
        sc.nextLine();
        char brr[] = sc.nextLine().toCharArray();
        
        for (int i = 0; i <= m; i++) f[0][i] = i;
        for (int i = 0; i <= n; i++) f[i][0] = i;
        
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = 1; j <= m; j++) {
    
    
                f[i][j] = Math.min(f[i-1][j] + 1, f[i][j-1] + 1);
                if (arr[i-1] == brr[j-1]) f[i][j] = Math.min(f[i][j], f[i-1][j-1]);
                else f[i][j] = Math.min(f[i][j], f[i-1][j-1] + 1);
            }
        }
        System.out.println(f[n][m]);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326094340&siteId=291194637