首页 > 试题广场 >

最大公共子串

[编程题]最大公共子串
  • 热度指数:4225 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个字符串,请编写代码,输出最长公共子串(Longest Common Substring),是指两个字符串中的最长的公共子串,要求子串一定是连续。

数据范围:输入的两个字符串长度满足

输入描述:
文本格式,2个非空字符串(字母数字组成),2个字符串以","英文逗号分割。


输出描述:
整形,为匹配到的最长子串长度
示例1

输入

bab,caba

输出

2
str1, str2 = input().split(",")
max_length = 0
for i in range(len(str1)):
    for j in range(len(str2)):
        if str1[i] == str2[j]:
            common = 0
            temp1 = i
            temp2 = j
            while temp1 < len(str1) and temp2 < len(str2):
                if str1[temp1] == str2[temp2]:
                    common += 1
                    temp1 += 1
                    temp2 += 1
                else:
                    break
            if max_length < common:
                max_length = common
print(max_length)
发表于 2024-04-30 16:44:28 回复(0)