给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
数据范围:
要求: 空间复杂度 ,时间复杂度
要求: 空间复杂度 ,时间复杂度
class Solution: def LCS3(self, str1: str, str2: str): m, n = len(str1), len(str2) top, digit =min(m, n), 0 while top//(10**digit)>10: digit += 1 while digit>=0: longest, index = 0, 0 for length in range(top, 0, -10**digit): for i in range(m - length + 1): if str1[i:i+length] in str2: longest = length index = i break if longest: break top = length+10**digit digit -= 1 return str1[index:index + longest]
class Solution: def LCS(self , str1: str, str2: str) -> str: # write code here m = len(str1) n = len(str2) d = [[0]*n for _ in range(m)] for j in range(n): d[0][j] = 1 if str1[0] == str2[j] else 0 for i in range(m): d[i][0] = 1 if str1[i] == str2[0] else 0 maxij = [0,0,0] for i in range(1,m): for j in range(1,n): if str1[i] == str2[j]: d[i][j] = 1+ d[i-1][j-1] if d[i][j] > maxij[0]: maxij = [d[i][j],i,j] return str1[1+maxij[1]-maxij[0]:1+maxij[1]]
class Solution: def LCS(self , str1: str, str2: str) -> str: # write code here m, n = len(str1), len(str2) dp = [[0] * (n + 1) for _ in range(m + 1)] end_index, max_length = 0, 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 dp[i][j] > max_length: max_length = dp[i][j] end_index = i return str1[end_index - max_length:end_index]
class Solution: def LCS(self , str1: str, str2: str) -> str: # write code here maxLen = 0 endIndex = 0 f = [[0 for j in range(len(str2)+1)] for i in range(len(str1)+1)] for i in range(1, len(str1)+1): for j in range(1, len(str2)+1): if (str1[i-1] == str2[j-1]): f[i][j] = f[i-1][j-1] + 1 else: f[i][j] = 0 if maxLen < f[i][j]: maxLen = f[i][j] endIndex = i # end index of the first string # print(maxLen) return str1[endIndex-maxLen:endIndex] # if len(str1) < len(str2): # str1, str2 = str2, str1 # res = '' # maxLen = 0 # for i in range(len(str1)): # if str1[i - maxLen: i+1] in str2: # res = str1[i-maxLen:i+1] # maxLen += 1 # 继续在原来长度上前行 # if len(res) == 0: # return -1 # return res
class Solution: def LCS(self , str1 , str2 ): # write code here if len(str1) < len(str2): str1, str2 = str2, str1 res = '' maxLen = 0 for i in range(len(str1)): if str1[i - maxLen: i+1] in str2: res = str1[i-maxLen:i+1] maxLen += 1 if len(res) == 0: return -1 return res