HDU-2328-Corporate Identity(利用string函数)

本文介绍了一种求解多个字符串中最长公共子串的方法,通过枚举与暴力匹配策略,利用C++ string函数实现,适用于如HDU-1238等类似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博主链接

题目链接

题意:

给你n个字符串,问你这n个串的最长公共子串

题解:

题目和HDU-1238感觉差不多,暴力枚举任意一个字符串的所有子串,然后暴力匹配,这里用string解决的;

代码:

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=4050;
const int mod=1e9+7;
string s[maxn];
int main(){
    int n;
    ios::sync_with_stdio(0);
    while((cin>>n)&&n!=0){
        for(int i=1;i<=n;i++){
            cin>>s[i];
        }
        string t;
        int cot=0;
        int maxx=0;
        int len=s[1].size();
        for(int i=0;i<len;i++){
            for(int j=1;j<=len-i;j++){      //枚举子串长度
                if(j<maxx)continue;
                cot=0;
                for(int k=2;k<=n;k++){
                    if(s[k].find(s[1].substr(i,j))==string::npos)break; //string函数查找
                    else cot++;
                }
                if(cot==n-1){	//如果这个子串出现了n-1次,选取的那个串本身就有一次,则维护maxx
                    if(maxx<j){		
                        maxx=j;
                        t=s[1].substr(i,j);
                    }
                    else if(maxx==j){
                        if(t>s[1].substr(i,j))t=s[1].substr(i,j);
                    }
                }
            }
        }
        if(maxx==0)cout<<"IDENTITY LOST"<<endl;
        else cout<<t<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值