PTA exercise-python 7-10 common substring search

Longest common substring search. A substring refers to a segment of consecutive characters in the original string.

Input format:

Enter two strings on a line-by-line basis, and find the longest substring common to both strings.

Output format:

Output the common substring.

Input sample:

A set of inputs is given here. For example:

Hefei Normal University
Anhui Hefei

Sample output:

The corresponding output is given here. For example:

Hefei

Idea analysis

1. Select a short string and use the short one to match the long one

2. Match the long strings one by one from the first of the short strings (double cycle), save the first identical string, remember the position, and recycle to match whether the next string of the two is the same (prerequisite: judge both Neither is the string at the last position, otherwise break), if the same, it will be saved, otherwise it will be broken, then break

3. The length of the common substring obtained each time is compared with the previous one, and if it is longer, it will be replaced

Code


str1=input()
str2=input()
# 选出短的那条,用短的去匹配长的
str_short,str_long= (list(str2),list(str1)) if len(str1)>len(str2) else (list(str1),list(str2))

s1 = ''
for i in range(len(str_short)):
    for k in range(len(str_long)):
        s2 =''  # 每次匹配都要清空s2
        y = k   # 记住此时k的值,以便后面找到相同串时,顺序匹配下一个串是否相同
        if str_short[i] == str_long[k]: #找到第一个相同的串,先记住
            s2 = s2 + str_short[i]
            for x in range(i,len(str_short)): #再找下一个是否相同
                if x!= len(str_short)-1 and y!= len(str_long)-1: # 先判断都不是最后一个位置的串
                    if str_short[x+1]==str_long[y+1]: # 相同则存起来
                        s2 = s2 + str_short[x+1]
                        y = y + 1  # 继续匹配下一个
                    else : # 否则就是不同,跳出
                        break
                else:
                    break
            if len(s2)>len(s1): # 如果后面得到的共同子串比前面的长,则替换
                s1 = s2
print(s1)

Submit results

 

Guess you like

Origin blog.csdn.net/weixin_58707437/article/details/128083061