mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
29 lines
540 B
Go
29 lines
540 B
Go
package leetcode
|
|
|
|
func longestCommonSubsequence(text1 string, text2 string) int {
|
|
if len(text1) == 0 || len(text2) == 0 {
|
|
return 0
|
|
}
|
|
dp := make([][]int, len(text1)+1)
|
|
for i := range dp {
|
|
dp[i] = make([]int, len(text2)+1)
|
|
}
|
|
for i := 1; i < len(text1)+1; i++ {
|
|
for j := 1; j < len(text2)+1; j++ {
|
|
if text1[i-1] == text2[j-1] {
|
|
dp[i][j] = dp[i-1][j-1] + 1
|
|
} else {
|
|
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
|
|
}
|
|
}
|
|
}
|
|
return dp[len(text1)][len(text2)]
|
|
}
|
|
|
|
func max(a, b int) int {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|