浙大数据结构ch9:KMP

[编程题]字符串匹配,可以用正则(有时间看看评论区的字典树)。regex 可以看 c++11的regex使用ios::sync_with_stdio(false)cin.tie(0) 可以加速IO

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

int main() {
    vector<string> strings;
    ios::sync_with_stdio(false); cin.tie(0);
    for (int n; cin >> n;) {
        strings.resize(n + 1);
        for (int i = 0; i <= n; ++i) cin >> strings[i]; //最后一个字符是pattern
        regex patt(strings.back(), regex_constants::ECMAScript | regex_constants::icase);
        for (int i = 0; i < n; ++i) {
            if (regex_match(strings[i], patt)) cout << i + 1 << ' ' << strings[i] << '\n';
        }
    }
}

[编程题]String Matching,用 find 即可解决,find 的第二个字符是给定字符串起始查找的位置

#include <bits/stdc++.h>

using namespace std;
int main() {
		string s,t;
		cin>>s>>t;
		int count=0,i=s.find(t);
		while(i!=-1){
			count++;
			i=s.find(t,i+1);
		}
		cout<<count;
		return 0;
}
#include <bits/stdc++.h>
using namespace std;

void BuildMatch(const string& patt,int *match){
    int i,j;
    match[0]=-1;
    int m=patt.size();
    for (j=1;j<m;j++){  //O(m)
        i=match[j-1];
        while ((i>=0) && (patt[i+1]!=patt[j])) i=match[i];  //找到之前已经匹配的前缀
        if (patt[i+1]==patt[j]) match[j]=i+1;   //i回退的次数不会超过增加的总次数
        else match[j]=-1;
        //printf("j=%d,i=%d\n",j,i);
    }
    //for (int i=0;i<m;i++) printf("match[%d]=%d\n",i,match[0]);
}

int KMP(const string& s,const string& patt){
    //设置两个指针sIndex和pIndex分别指向正在比较的两个字符
    int n=s.size();         //O(n)
    int m=patt.size();      //O(m)
    int sIndex=0,pIndex=0;
    int* match=new int[m];
    BuildMatch(patt,match);
    //for (int i=0;i<m;i++) printf("match[%d]=%d\n",i,match[0]);
    while (sIndex<n && pIndex<m){   //O(n)
        //printf("sIndex=%d,pIndex=%d\n",sIndex,pIndex);
        if (s[sIndex]==patt[pIndex]){
            sIndex++;
            pIndex++;
        }
        else if (pIndex>0) pIndex=match[pIndex-1]+1; //直接位移到匹配的前缀那里
        else sIndex++;
    }
    //printf("pIndex=%d\n",pIndex);
    return (pIndex==m)?(sIndex-m):-1;
}
int main(){
    string s="This is a simple example.";
    string patt="simple";
    int i=KMP(s,patt);
    //printf("i=%d\n",i);
    if (i==-1) printf("Not found.\n");
    else printf("%c",s[i]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_森罗万象

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

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

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

打赏作者

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

抵扣说明:

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

余额充值