-
Notifications
You must be signed in to change notification settings - Fork 1
/
lcs.py
29 lines (26 loc) · 885 Bytes
/
lcs.py
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
# Problem: Longest Common Subsequence
# Author: Mashu Ajmera
# Algorithm: Dynamic Programming
# Leetcode: https://leetcode.com/problems/longest-common-subsequence/submissions/
# GFG: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
class Solution:
def longestCommonSubsequence(self,a,b):
la=len(a)
lb=len(b)
dp=[[0 for i in range(lb+1)] for j in range(la+1)]
print(dp[0])
for i in range(1,la+1):
for j in range(1,lb+1):
if i==0 or j==0:
dp[i][j]=0
elif a[i-1]==b[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
# print(dp[i])
return dp[la][lb]
if __name__=="__main__":
a="GXTXAYB"
b="AGGTAB"
s=Solution()
print(s.longestCommonSubsequence(a,b))