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

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

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

while True:
    try:
        s1=input()
        s2=input()
        if len(s1)>len(s2):#总体思路:从短的字符串中取子串,看其在长字符串中是否存在
            s1,s2=s2,s1
        length=0
        for i in range(len(s1)):
            for j in range(i+1,len(s1)):
                sub=s1[i:j]
                if sub in s2 and j-i>length:
                    res=sub
                    length=j-i
        print(res)
    except:
        break
#和python的解法本质上是一样的,不过细节上要注意,比如substr()函数第二个参数是子串的长度
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s1,s2,temp;
    while(cin >> s1 >> s2){
        if(s1.size() > s2.size())
            swap(s1,s2);
        string sub,res;
        int length=0;
        for(int i=0;i<s1.size();i++){
            for(int j=i+1;j<s1.size();j++){
                sub=s1.substr(i,j-i+1);
                if(s2.find(sub)==-1)
                    break;
                else if(sub.size()>res.size())
                    res=sub;
            }
            }
        cout << res << endl;
        }
    return 0;
    }


全部评论
j in range(i+1,len(str1)+1) 否则会少最后一个字符
1 回复 分享
发布于 2021-02-19 03:28
可以从长到短来查找,查找到第一个输出就行了
点赞 回复 分享
发布于 2022-05-14 16:08
if len(short) == 1 and short in long: print(short) break short等于1的情况 没考虑
点赞 回复 分享
发布于 2022-01-26 10:56
切片的最后一个范围是s[:len(s)]
点赞 回复 分享
发布于 2022-01-04 21:31
应该是for j in range(i+1,len(s1)+1):
点赞 回复 分享
发布于 2021-08-05 11:00
一开始加一个res = '' 吧
点赞 回复 分享
发布于 2021-07-11 12:17

相关推荐

评论
13
1
分享

创作者周榜

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