Longest Common Subsequence
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, “ace” is a subsequence of “abcde” while “aec” is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example
Input: text1 = “abcde”, text2 = “ace”
Output: 3
Explanation: The longest common subsequence is “ace” and its length is 3.
Solution
func longestCommonSubsequence(text1 string, text2 string) int {
m, n := len(text1), len(text2)
A, B := []byte(text1), []byte(text2)
pre := make([]int, m+1)
cur := make([]int, m+1)
for j:=0;j<n;j++{
for i:=0;i<m;i++{
temp := max(pre[i+1], cur[i])
if B[j]==A[i]{
cur[i+1] = max(temp, pre[i]+1)
} else{
cur[i+1] = temp
}
}
cur, pre = pre, cur
}
return pre[m]
}
func max(a,b int)int {
if a>b{
return a
}
return b
}