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;
    }
}

 

 

 

posted @ 2021-04-07 15:06  Coder-Jiang  阅读(3)  评论(0编辑  收藏  举报  来源