python 查找兩個字符串a,b中的最長公共子串


地址:https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506?tpId=37&&tqId=21288&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking

 

 1 '''
 2 描述
 3 查找兩個字符串a,b中的最長公共子串。若有多個,輸出在較短串中最先出現的那個。
 4 注:子串的定義:將一個字符串刪去前綴和后綴(也可以不刪)形成的字符串。請和“子序列”的概念分開!
 5 
 6 本題含有多組輸入數據!
 7 輸入描述:
 8 輸入兩個字符串
 9 
10 輸出描述:
11 返回重復出現的字符
12 示例1
13 輸入:
14 abcdefghijklmnop
15 abcsafjklmnopqrstuvw
16 輸出:
17 jklmnop
18 
19 '''
20 
21 while(True):
22     try:str1 = input()
23     except:break
24 
25     str2 = input()
26     newStr = ''
27     resStr=''
28     resStrShort = str1 if len(str1) <= len(str2) else str2
29     for i in range(len(str1)):
30         newStr = str1[i:]
31         for j in range(len(newStr)):
32             newStr1 = newStr[:len(newStr)-j]
33             if newStr1 in str2:
34 
35                 if len(resStr) > len(newStr1) or (len(resStr) == len(newStr1) and resStrShort.index(resStr) < resStrShort.index(newStr1)):
36                     resStr = resStr
37                 else:
38                     resStr = newStr1
39     print(resStr)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM