给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
数据范围:
要求: 空间复杂度 ,时间复杂度
要求: 空间复杂度 ,时间复杂度
class Solution: def LCS(self , str1 , str2 ): dp = [ [''] * (len(str2) + 1) for _ in range(len(str1) + 1)] ans = '' for i in range(1, len(str1)+1): for j in range(1, len(str2)+1): if str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] + str1[i-1] ans = dp[i][j] if len(dp[i][j]) >= len(ans) else ans else: dp[i][j] = '' return ans
# # longest common substring # @param str1 string字符串 the string # @param str2 string字符串 the string # @return string字符串 # class Solution: def LCS(self , str1 , str2 ): # write code here strlen1 = len(str1) strlen2 = len(str2) record = [[0 for i in range(strlen2+1)] for j in range(strlen1+1)] maxnum = 0 p = 0 for i in range(strlen1): for j in range(strlen2): if str1[i] == str2[j]: record[i+1][j+1] = record[i][j]+1 if record[i+1][j+1] > maxnum: maxnum = record[i+1][j+1] p = i +1 return str1[p-maxnum: p]
class Solution: def LCS(self , str1 , str2 ): a, b = '', '' for i in str1: a += i if a in str2: b = a else: a = a[1:] return b
class Solution: def LCS(self, str1, str2): maxStr = str1 if len(str1) > len(str2) else str2 minStr = str2 if len(str1) > len(str2) else str1 Str = "" max = "" if maxStr == minStr: return maxStr for i in range(len(minStr)): index = maxStr.find(minStr[i]) if index >= 0: s = maxStr[index:] s2 = minStr[i:] for z in range(len(s2)): Str = Str + s2[z] if s.find(Str) < 0: break max = Str[:-1] if len(Str[:-1]) > len(max) else max Str = "" return max if max else 0
def longestCommonSubsequence(self, text1, text2): """ :type text1: str :type text2: str :rtype: int """ m=len(text1) n=len(text2) dp = [[0 for i in range(n+1)] for j in range(m+1)] for i in range(1, m+1): for j in range(1, n+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[m][n]本题区别在于如果 str1[i-1] != str2[j-1]说明不是连续的子串,那么不做处理,只处理str1[i-1] == str2[j-1]的情况,使用maxlen记录最长的连续子串的长度,index记录最长连续子串末尾的序号。
class Solution: def LCS(self , str1 , str2 ): # write code here m=len(str1) n=len(str2) dp = [[0 for i in range(n+1)] for j in range(m+1)] maxlen = 0 index = 0 for i in range(1, m+1): for j in range(1, n+1): if str1[i-1] == str2[j-1]: dp[i][j]=dp[i-1][j-1]+1 if maxlen<dp[i][j]: maxlen=dp[i][j] index=i if maxlen==0: return '' else: return str1[index-maxlen:index]