Skip to content

Commit 602dd86

Browse files
committed
DP # LCS
1 parent ed5563e commit 602dd86

File tree

3 files changed

+38
-5
lines changed

3 files changed

+38
-5
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def longest_common_subsequence(sequence1, sequence2):
2+
cols = len(sequence1) + 1 # Add 1 to represent 0 valued column for DP
3+
rows = len(sequence2) + 1 # Add 1 to represent 0 valued row for DP
4+
5+
T = [[0 for _ in range(cols)] for _ in range(rows)]
6+
7+
max_length = 0
8+
9+
for i in range(1, rows):
10+
for j in range(1, cols):
11+
if sequence2[i - 1] == sequence1[j - 1]:
12+
T[i][j] = 1 + T[i - 1][j - 1]
13+
else:
14+
T[i][j] = max(T[i - 1][j], T[i][j - 1])
15+
16+
max_length = max(max_length, T[i][j])
17+
18+
return max_length
19+

CP/January Challenge 2018/string.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def longest_common_subsequence(sequence1, sequence2):
2+
cols = len(sequence1) + 1 # Add 1 to represent 0 valued column for DP
3+
rows = len(sequence2) + 1 # Add 1 to represent 0 valued row for DP
4+
5+
T = [[0 for _ in range(cols)] for _ in range(rows)]
6+
7+
max_length = 0
8+
9+
for i in range(1, rows):
10+
for j in range(1, cols):
11+
if sequence2[i - 1] == sequence1[j - 1]:
12+
T[i][j] = 1 + T[i - 1][j - 1]
13+
else:
14+
T[i][j] = max(T[i - 1][j], T[i][j - 1])
15+
16+
max_length = max(max_length, T[i][j])
17+
18+
return max_length
19+

dynamic/longest_common_subsequence.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,6 @@
55
Given two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find the length of the longest common
66
subsequence.
77
8-
Video
9-
-----
10-
11-
* https://youtu.be/NnD96abizww
12-
138
Complexity
149
----------
1510

0 commit comments

Comments
 (0)