详细注释版 | #公共子串计算#

公共子串计算

https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

while True:
    try:
        s1, s2 = input(), input()
        # 确保 s1 为较短的字符串(也可等长)
        if len(s1) > len(s2):
            s1, s2 = s2, s1
        max_len = 0
        # 遍历s1中的字符作为子串的起始字符
        for i in range(len(s1)):
            # 可能的公共子串长度为(0, len(s1)-i+1)
            for L in range(len(s1)-i+1):
                    # 从s1中截取的子串在s2中且截取长度>当前最大长度,则更新最大长度
                    if s1[i:i+L] in s2 and L > max_len:
                        max_len = L
        print(max_len)
    except:
        break

全部评论

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务