24 lines
620 B
Go
24 lines
620 B
Go
package q1143
|
|
|
|
// Note: Can be compressed to only len(text1) extra space.
|
|
|
|
func longestCommonSubsequence(text1 string, text2 string) int {
|
|
commonSeqLen := make([][]int, len(text1)+1)
|
|
for i := range commonSeqLen {
|
|
commonSeqLen[i] = make([]int, len(text2)+1)
|
|
}
|
|
|
|
for i1 := 1; i1 <= len(text1); i1++ {
|
|
for i2 := 1; i2 <= len(text2); i2++ {
|
|
if text1[i1-1] == text2[i2-1] {
|
|
commonSeqLen[i1][i2] = commonSeqLen[i1-1][i2-1] + 1
|
|
} else {
|
|
commonSeqLen[i1][i2] = max(commonSeqLen[i1-1][i2], commonSeqLen[i1][i2-1])
|
|
}
|
|
}
|
|
}
|
|
|
|
return commonSeqLen[len(text1)][len(text2)]
|
|
}
|
|
|
|
var _ = longestCommonSubsequence
|