Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
裸的最长公共子序列,复杂度O(mn)

 1 #1143
 2 #Runtime: 255 ms (Beats 94.79%)
 3 #Memory: 21.6 MB (Beats 79.65%)
 4 
 5 class Solution(object):
 6     def longestCommonSubsequence(self, text1, text2):
 7         """
 8         :type text1: str
 9         :type text2: str
10         :rtype: int
11         """
12         dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
13         for i in range(1, len(text1) + 1):
14             for j in range(1, len(text2) + 1):
15                 if text1[i - 1] == text2[j - 1]:
16                     dp[i][j] = dp[i-1][j-1] + 1
17                 else:
18                     dp[i][j] = max(dp[i-1][j], dp[i][j - 1])
19         return dp[len(text1)][len(text2)]


只开两个一维dp数组的版本:

 1 #1143
 2 #Runtime: 222 ms Beats 99.2%)
 3 #Memory: 13.6 MB (Beats 96.7%)
 4 
 5 class Solution(object):
 6     def longestCommonSubsequence(self, text1, text2):
 7         """
 8         :type text1: str
 9         :type text2: str
10         :rtype: int
11         """
12         dp = [0] * (len(text2) + 1)
13         dp_pre = [0] * (len(text2) + 1)
14         for i in range(1, len(text1) + 1):
15             for j in range(1, len(text2) + 1):
16                 if text1[i - 1] == text2[j - 1]:
17                     dp[j] = dp_pre[j-1] + 1
18                 else:
19                     dp[j] = max(dp_pre[j], dp[j - 1])
20             dp_pre = dp
21             dp = [0] * (len(text2) + 1)
22         return dp_pre[len(text2)]


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理