Written interview questions: edit distance

      Originally published in:

 

 

      Edit distance can be used to measure the difference between two strings. Its meaning is: the minimum number of transformations from one character string to another character string, where the transformation operation only involves addition, deletion, and modification, and only one character can be operated at a time.

      Edit distance is widely used, such as error correction and error detection:

    

 

      Edit distance is often involved in written interviews. A friend recently participated in an interview with T company, and met the edit distance:

   

      Edit distance is a typical dynamic programming problem. So, does the edit distance from one string to another must exist? This is inevitable, and violent methods can be proved, so there is no need to repeat it.

 

      Let dp[i][j] be the edit distance from the first i characters of string A to the first j characters of string B. If A or B is an empty string, then i or j is 0, so the interval of i is The interval of [0, lenA], j is [0, lenB]. Next, we derive the dynamic programming equation.

       (1) If A[i] is equal to B[j], then it is a lying-to-win mode at this time, namely:

dp[i][j] = dp[i-1][j-1]

       (2) If A[i] is not equal to B[j], three operations (addition, deletion, modification) can be performed, as follows:

        a. Change the first i-1 characters of A into the first j characters of B, and then delete one character;

        b. Change the first i characters of A into the first j-1 characters of B, and then add a character;

        c. Change the first i-1 characters of A to the first j-1 characters of B, and then change a character;

        Obviously, the dynamic programming equation at this time is:

        dp[i][j] = 1 + min{dp[i-1][j],dp[i][j-1],dp[i-1][j-1]}

        

       After the algorithm is understood, the program is simple:​​​​​​

func minDistance(A string, B string) int {
    lenA := len(A)
    lenB := len(B)

    // 初始化二维slice
    dp := make([][]int, lenA + 1)
    for i := 0; i < lenA + 1; i++ {
        dp[i] = make([]int, lenB + 1)
    }

    for i := 0; i < lenA + 1; i++ {
        dp[i][0] = i
    }

    for j := 0; j < lenB + 1; j++ {
        dp[0][j] = j
    }

    for i := 1; i < lenA + 1; i++ {
        for j := 1; j < lenB + 1; j++ {
            if A[i - 1] == B[j - 1] {
                dp[i][j] = dp[i-1][j-1]
            }else {
                dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
            }
        }
    }

    return dp[lenA][lenB]
}

func min(x, y, z int) int {
    m := x
    if x > y {
        m = y
    }

    if m > z {
        m = z
    }

    return m
}

 

       Tested on Leetcode and passed.

 

       Have a nice weekend, and I wish fresh graduates and social recruits a better offer.

 

Guess you like

Origin blog.csdn.net/stpeace/article/details/110419493