From 3fd56c0f8a52355ccb78f08e5e3eb6656d3fd1be Mon Sep 17 00:00:00 2001 From: ashing Date: Thu, 25 Jan 2024 23:02:17 +0800 Subject: [PATCH] feat: 1143. Longest Common Subsequence Signed-off-by: ashing --- .../1143/1143. Longest Common Subsequence.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 leetcode/1143/1143. Longest Common Subsequence.go diff --git a/leetcode/1143/1143. Longest Common Subsequence.go b/leetcode/1143/1143. Longest Common Subsequence.go new file mode 100644 index 0000000..2ccc26a --- /dev/null +++ b/leetcode/1143/1143. Longest Common Subsequence.go @@ -0,0 +1,28 @@ +package _143 + +func longestCommonSubsequence(text1 string, text2 string) int { + m, n := len(text1), len(text2) + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if text1[i-1] == text2[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else { + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + } + } + } + + return dp[m][n] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +}