L2-4 串的模式匹配

输入样例:

abcabcabcabcacabxy
3
abcabcacab
cabcabcd
abcabcabcabcacabxyz

输出样例:

abcabcacabxy
Not Found
Not Found

 思路:

寻找子串问题?在学习C++STL的时候依稀记得可以使用find函数来寻找某子串在字符串中出现的第一个位置,那就用呗,看看能不能过

参考代码(使用find函数——超时):

#include<bits/stdc++.h>
using namespace std;
// 使用C++的find超时
int main() {
    string String, Pattern;  cin>>String;
    int n;  cin>>n;
    while(n--) {
        cin>>Pattern;
        int index = String.find(Pattern, 0);
        cout<< (index!=String.npos? String.substr(index): "Not Found") <<endl;
    }
    return 0;
}

 结果与预想的一样,面对100W长度的字符串找10W长度的子串,确实有点蚍蜉撼树。不过看了汪哥的代码,不禁感慨C语言才是yyds!!

参考代码(使用strstr函数——AC):

#include<bits/stdc++.h>
using namespace std;
// 使用C语言提供的strstr函数查找子串出现的第一个位置
int main() {
    string String, Pattern;
    int n;
    cin >> String >> n;
    while(n--) {
        cin >> Pattern;
        const char* p = strstr(String.c_str(), Pattern.c_str());    // c_str()将字符串(string)转换为字符数组(const char*)
        cout<< (p!=NULL? p: "Not Found") <<endl;
    }
    return 0;
}

 参考代码(KMP解法——AC):

#include <bits/stdc++.h>
using namespace std;
#define N 100005

void get_next(string str,int *next){
    int i=0,j=-1;                      
    next[0]=-1;
    int a=str.size();
    while(i<a){                         
        if(j==-1||str[i]==str[j]){      
            i++;j++;
            if(str[i]!=str[j])          //优化
                next[i]=j;
            else
                next[i]=next[j];
        }
        else
            j=next[j];
    }
}

int kmp(string strA,string strB,int* next){
    int i=-1,j=-1;
    int a=strA.size(),b=strB.size();
    while(i<a && j<b){
        if(j==-1 || strA[i]==strB[j]){
            i++;j++;
        }
        else
            j=next[j];
    }
    if(j >= b)  return i-b;           //匹配成功返回位置
    else    return -1;
}

int main() {
    string strA,strB;
    cin>>strA;
    int n;
    cin>>n;
    int next[N];
    while(n--) {
        cin>>strB;
        get_next(strB,next);
        int pos=kmp(strA,strB,next);
        int a=strA.size();
        if(pos!=-1) {
            for(int i=pos; i<a; i++)
                cout<<strA[i];
            cout<<endl;
        }
        else
            cout<<"Not Found"<<endl;
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「江太白」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值