python 遍历字符串一遍解法

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/questionTerminal/181a1a71c7574266ad07f9739f791506

从较短的字符串从头到尾遍历一遍即可:设置一个初始最大公共子串长度 max_length = 0,当遍历到s1[i]时,若s1[i:i+max_length+1] in s2,则最大公共子串长度可增加1,继并续判断直至不满足条件时,i 增加 1,即遍历到 i+1的位置,以此类推。由于仅需要输出较短字符串中最早出现的最长公共子串,因此 max_length 遇到更大的满足条件时才需更新,若后续遍历没有再比当前得到的 max_length 更长的子串,则无需更新,因此从较短的字符串从头到尾遍历一遍即可。

while True:
    try:
        s1 = input().strip()
        s2 = input().strip()
        if len(s1) > len(s2):
            s1,s2 = s2,s1
        res = ''
        max_length = 0
        i = 0
        while i + max_length < len(s1):
             while i+max_length < len(s1) and s1[i:i+max_length+1] in s2:
             #这里一定需要再判别一下i+max_length < len(s1),否则会出现无限循环的情况,测试用例不全所以才没有报错
                res = s1[i:i+max_length+1]
                max_length += 1
            i += 1
        print(res)
    except:
        break
全部评论
我给你一个示例,你输出一下: abc dabddabcef 它应该输出abc而不是输出ab(排名前两位的的就是输出ab)或者像你这个直接死循环 这一题验证的示例有bug,不够全面 另外付一下我的代码: # 思路一:对短串“前后夹逼(遍历)”,这样子只要找到第一个符合要求的这一轮循环就可以停止 while True: try: shorter, longer = sorted([input(), input()], key=len) res_li = [] l = len(shorter) # print(f'短:{shorter}', f'长:{longer}') for i in range(l): for j in range(l-1, -1, -1): s = shorter[i:j+1] if s in longer: res_li.append(s) break print(max(res_li, key=len) if len(res_li) != 0 else '') except EOFError: break
点赞 回复
分享
发布于 2021-03-09 21:44
你确定这是O(n)复杂度?
点赞 回复
分享
发布于 2021-03-23 17:50
滴滴
校招火热招聘中
官网直投

相关推荐

点赞 评论 收藏
转发
3 3 评论
分享
牛客网
牛客企业服务