首页 技术 正文
技术 2022年11月18日
0 收藏 977 点赞 2,754 浏览 1564 个字
 """
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
""" """
提交显示wrong answer,但在IDE是对的
其实这个代码很冗余,应该是 超时
"""
class Solution1:
def longestCommonSubsequence(self, text1, text2):
res1, res2 = 0, 0
i, j = 0, 0
while i < len(text1) and j < len(text2):
if text1[i] == text2[j]:
res1 += 1
i += 1
j += 1
else:
if len(text1) - i < len(text2) - j: #第二遍循环是为了处理这个
i += 1
else:
j += 1
i, j = 0, 0
while i < len(text1) and j < len(text2):
if text1[i] == text2[j]:
res2 += 1
i += 1
j += 1
else:
if len(text1) - i > len(text2) - j:
i += 1
else:
j += 1
res = max(res1, res2)
return res """
经典的动态规划,用一个二维数组,存当前的结果
如果值相等:dp[i][j] = dp[i-1][j-1] + 1
如果值不等:dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 左边和上边的最大值
在矩阵 m行n列容易溢出,这点很难把握
目前的经验,每次严格按照行-列的顺序进行
"""
class Solution:
def longestCommonSubsequence(self, text1, text2):
n = len(text1)
m = len(text2)
dp = [[0]*(m+1) for _ in range(n+1)] #建立 n+1行 m+1列矩阵,值全为0
for i in range(1, n+1): #bug 内外循环层写反了,导致溢出,n+1 * m+1 矩阵
for j in range(1, m+1):
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898