Skip to content

Commit 6beac18

Browse files
authored
Merge pull request #1 from TheAlgorithms/master
Update
2 parents fbf6eb0 + dd65dd3 commit 6beac18

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
## Dynamic-Programming
2525
* [Longest-Palindromic-Subsequence](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/longest-palindromic-subsequence.go)
26+
* [Longestcommonsubsequence](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/longestCommonSubsequence.go)
2627
* [Matrix-Multiplication](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/matrix-multiplication.go)
2728
* [Rod-Cutting](https://github.com/TheAlgorithms/Go/blob/master/dynamic-programming/rod-cutting.go)
2829

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// LONGEST COMMON SUBSEQUENCE
2+
// DP - 4
3+
// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
4+
5+
package longestcommonsubsequence
6+
// package main
7+
8+
// import "fmt"
9+
10+
func max(a,b int) int{
11+
if a>b{
12+
return a
13+
}
14+
return b
15+
}
16+
17+
func longestCommonSubsequence(a string, b string, m int, n int) int{
18+
// m is the length of string a and n is the length of string b
19+
20+
// here we are making a 2d slice of size (m+1)*(n+1)
21+
lcs:= make([][] int, m+1)
22+
for i:=0;i<=m;i++{
23+
lcs[i] = make([]int, n+1)
24+
}
25+
26+
// block that implements LCS
27+
for i:=0;i<=m;i++{
28+
for j:=0;j<=n;j++{
29+
if i==0 || j==0{
30+
lcs[i][j] = 0;
31+
}else if a[i-1] == b[j-1]{
32+
lcs[i][j] = lcs[i-1][j-1]+1
33+
}else{
34+
lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1])
35+
}
36+
}
37+
}
38+
// returning the length of longest common subsequence
39+
return lcs[m][n]
40+
}
41+
42+
// func main(){
43+
// // declaring two strings and asking for input
44+
45+
// var a,b string
46+
// fmt.Scan(&a, &b)
47+
// // calling the LCS function
48+
// fmt.Println("The length of longest common subsequence is:", longestCommonSubsequence(a,b, len(a), len(b)))
49+
// }

0 commit comments

Comments
 (0)