-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
longestcommonsubsequence.go
40 lines (35 loc) · 1.07 KB
/
longestcommonsubsequence.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// LONGEST COMMON SUBSEQUENCE
// DP - 4
// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
// https://leetcode.com/problems/longest-common-subsequence/
// time complexity: O(m*n) where m and n are lengths of the strings
// space complexity: O(m*n) where m and n are lengths of the strings
package dynamic
func strToRuneSlice(s string) (r []rune, size int) {
r = []rune(s)
return r, len(r)
}
// LongestCommonSubsequence function
func LongestCommonSubsequence(a string, b string) int {
aRunes, aLen := strToRuneSlice(a)
bRunes, bLen := strToRuneSlice(b)
// here we are making a 2d slice of size (aLen+1)*(bLen+1)
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i := 0; i <= aLen; i++ {
for j := 0; j <= bLen; j++ {
if i == 0 || j == 0 {
lcs[i][j] = 0
} else if aRunes[i-1] == bRunes[j-1] {
lcs[i][j] = lcs[i-1][j-1] + 1
} else {
lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])
}
}
}
// returning the length of longest common subsequence
return lcs[aLen][bLen]
}