有两个字符串(可能包含空格),请找出其中最长的公共连续子串,输出其长度。
def longest_com_substring(s1, s2): n1, n2 = len(s1), len(s2) dp = [[0, ] * n2 for _ in range(n1)] # i为s1的下标,j为s2的下标,dp[i][j]表示以s[i],s[j]结尾的最长公共子串的长度 ans = 0 # 当j=0的时候 for i in range(n1): if s1[i] == s2[0]: dp[i][0] = ans = 1 # 当i=0的时候 for j in range(n2): if s1[0] == s2[j]: dp[0][j] = ans = 1 # dp[i][j] == dp[i - 1][j - 1] for j in range(1, n2): for i in range(1, n1): if s1[i] == s2[j]: p = dp[i - 1][j - 1] if p != 0: dp[i][j] = p + 1 else: dp[i][j] = 1 ans = dp[i][j] if dp[i][j] > ans else ans return ans