longest common subsequence - golang

topic:

Given two strings str1 and str2, return the longest common subsequence of the two strings

Example:

str1 = "1A2C3D4B56"

str2 = "B1D23CA45B6A"

Their longest common subsequence is: "123456" or "12C4B6"

Problem solving method:

The classic dynamic programming method:

According to the state equation, the state array dp generated by str1 and str2 can be obtained. The code is as follows:

func GetDp(arr1, arr2 []rune)[][]int{
    dp := make([][]int, len(arr1))
    for k, _ := range dp{
        dp[k] = make([]int, len(arr2))
    }
    if arr1[0] == arr2[0]{
        dp[0][0] = 1
    }else{
        dp[0][0] = 0
    }
    for i:=1;i<len(arr1);i++{//Calculate the first column
        if arr1[i] == arr2[0]{
            dp[i][0] = 1
        }else{
            dp[i][0] = dp[i-1][0]
        }
    }
    for i:=1;i<len(arr2);i++{//Calculate the first line
        if arr2[i] == arr1[0]{
            dp[0][i] = 1
        }else{
            dp[0][i] = dp[0][i-1]
        }
    }
    for i:=1;i<len(arr1);i++{//The rest
        for j:=1;j<len(arr2);j++{
            if arr1[i] == arr2[j]{
                dp[i][j] = dp[i-1][j-1]+1
            }else{
                dp[i][j] = getMax(dp[i-1][j], dp[i][j-1])
            }
        }
    }
    return dp
}

 For the two strings in the example, the dp array can be obtained as follows:

[ [0 0 0 0 0 0 0 1 1 1]

 [1 1 1 1 1 1 1 1 1 1] 

 [1 1 1 1 1 2 2 2 2 2]

 [1 1 2 2 2 2 2 2 2 2]

 [1 1 2 2 3 3 3 3 3 3]

 [1 1 2 3 3 3 3 3 3 3]

 [1 2 2 3 3 3 3 3 3 3]

 [1 2 2 3 3 3 4 4 4 4]

 [1 2 2 3 3 3 4 4 5 5]

 [1 2 2 3 3 3 4 5 5 5]

 [1 2 2 3 3 3 4 5 5 6]

 [1 2 2 3 3 3 4 5 5 6]]

When searching for a common subsequence, start from the lower right corner and move up, up, left and left. If the value of the current position is the same as the value on the left or above, move to the left or up, if not, move to the upper left Move, their difference is 1, the search code is as follows:

func GetRes(dp [][]int, arr1 []rune, arr2 []rune)[]rune{
    m, n: = len (arr1) -1, len (arr2) -1
    res := make([]rune, dp[m][n])
    index := len(res) -1
    for index >= 0 {
        if n>0 && dp[m][n] == dp[m][n-1]{
            n--
        }else if m > 0 && dp[m][n] == dp[m-1][n]{
            m--
        }else{
            res[index] = arr1[m]
            index --
            m--
            n--
        }
    }
    return res
}

  

Guess you like

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