Skip to content

Commit e18641c

Browse files
author
Chris Wu
committed
no message
1 parent 14bbaa2 commit e18641c

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution(object):
2+
def longestCommonSubsequence(self, text1, text2):
3+
M, N = len(text1), len(text2)
4+
5+
#dp[i][j] := logest subsequence of text1[0:i-1] and text[0:j-1]
6+
dp = [[0 for _ in xrange(N+1)] for _ in xrange(M+1)]
7+
8+
for i in xrange(1, M+1):
9+
for j in xrange(1, N+1):
10+
if text1[i-1]==text2[j-1]:
11+
dp[i][j] = dp[i-1][j-1]+1
12+
else:
13+
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
14+
15+
return dp[M][N]
16+
17+
"""
18+
Time: O(MN)
19+
Space: O(MN)
20+
"""
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution(object):
2+
def findLength(self, A, B):
3+
M, N = len(A), len(B)
4+
5+
#dp[i][j] := the logest length of sub array that needs to involve A[i] and B[j]
6+
dp = [[0 for _ in xrange(N+1)] for _ in xrange(M+1)]
7+
8+
for i in xrange(1, M+1):
9+
for j in xrange(1, N+1):
10+
if A[i-1]==B[j-1]:
11+
dp[i][j] = dp[i-1][j-1]+1
12+
13+
return max(max(row) for row in dp)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution(object):
2+
def minimumDeleteSum(self, s1, s2):
3+
N, M = len(s1), len(s2)
4+
dp = [[float('inf') for _ in xrange(M+1)] for _ in xrange(N+1)]
5+
6+
dp[0][0] = 0
7+
8+
for i in xrange(1, N+1):
9+
dp[i][0] = dp[i-1][0]+ord(s1[i-1])
10+
11+
for j in xrange(1, M+1):
12+
dp[0][j] = dp[0][j-1]+ord(s2[j-1])
13+
14+
for i in xrange(1, N+1):
15+
for j in xrange(1, M+1):
16+
if s1[i-1]==s2[j-1]:
17+
dp[i][j] = min(dp[i][j], dp[i-1][j-1])
18+
dp[i][j] = min(dp[i][j], dp[i][j-1]+ord(s2[j-1]), dp[i-1][j]+ord(s1[i-1]))
19+
20+
return dp[N][M]
21+
22+
"""
23+
Time: O(MN)
24+
Space: O(MN)
25+
"""

0 commit comments

Comments
 (0)