Skip to content

Commit afd4ace

Browse files
committed
最长公共子序列
1 parent 717e7d9 commit afd4ace

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

longest_common_subsequence.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param A, B: Two strings.
6+
@return: The length of longest common subsequence of A and B.
7+
"""
8+
def longestCommonSubsequence(self, A, B):
9+
# write your code here
10+
self.ret = 0
11+
self.cache = [[-1] * len(A) for i in xrange(len(B))] # 缓存,避免重复计算
12+
self._longestCommonSubsequence(A, B, 0, 0)
13+
return self.ret
14+
15+
def _longestCommonSubsequence(self, A, B, start_a, start_b):
16+
if (start_a >= len(A)) or (start_b >= len(B)):
17+
return 0
18+
elif self.cache[start_a][start_b] == -1:
19+
if A[start_a] != B[start_b]:
20+
len_a = self._longestCommonSubsequence(A, B, start_a + 1, start_b)
21+
len_b = self._longestCommonSubsequence(A, B, start_a, start_b + 1)
22+
self.ret = max(max(len_a, len_b), self.ret) # LCS不要求连续
23+
self.cache[start_a][start_b] = max(len_a, len_b)
24+
else:
25+
_len = self._longestCommonSubsequence(A, B, start_a + 1, start_b + 1)
26+
self.ret = max(_len + 1, self.ret)
27+
self.cache[start_a][start_b] = _len + 1
28+
return self.cache[start_a][start_b]

0 commit comments

Comments
 (0)