最长子串 | HJ65 查找两个字符串a,b中的最长公共子串
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506?tpId=37&tqId=21288&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
while True: try: s1 = input() s2 = input() n = 0 max_sub = '' if len(s2)<len(s1): s1, s2 = s2, s1 for i in range(len(s1)): if s1[i-n:i+1] in s2: max_sub = s1[i-n:i+1] n += 1 print(max_sub) except: break
令n为最长子串的长度,遍历短字符串s的索引i,套用s[i-n:i+1]模板
s[i-n:i+1]模板:
1、截取(n+1)长度的子串,若n长度的子串末尾再添加1个字符也满足条件,则给最长子串的长度记录值n加上1
2、s[i-n:i+1]中第一个索引 i-n:根据n长度决定下一个子串起始位置
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107