7-1 串的模式匹配(KMP解法和strstr解法)

本文对比了KMP算法和标准库函数strstr的字符串模式匹配方法,通过实例展示了如何使用KMP算法实现精确搜索,并介绍了strstr函数在快速查找子串方面的应用。适合理解这两种经典算法在实际编程中的应用。

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

串的模式匹配

题目

请添加图片描述

KMP解法

#include<bits/stdc++.h>

using namespace std;

char s[1000010],q[100010];
int ne[100010];
int n;



int main()
{
	cin>>s+1>>n;
	while(n--){
		cin>>q + 1;
		ne[1] = -1;	
		for(int i = 2 , j = 0 ; q[i] != '\0' ; i ++){
			
			while(j && q[j + 1] != q[i]) j = ne[j];
			
			if(q[j + 1] == q[i]) j ++;
			
			ne[i] = j;
		}
		
		int ans = -1;
		
		for(int i = 1 , j = 0; s[i] != '\0'  ; i ++){
			while(j && q[j + 1] != s[i]) j = ne[j];
			if(q[j + 1] == s[i]) j ++;
			
			if(q[j + 1] == '\0'){
				ans = i - j ;
				break;
			}
		}		
		
		if(ans == -1) cout<<"Not Found";
		else{
//			for(int i = ans ; s[i] != '\0' ; i ++) cout<<s[i];
//			cout<<"\0";
//			cout<<endl;
			cout<<s+ans+1;
		}
		
		if(n) cout<<endl;
	}
	return 0;
 } 

strstr解法:

#include<iostream>
#include<string.h>
using namespace std;
const int N = 1e6 + 10;

char s[N],q[N];
int n;

int main()
{
    cin>>s>>n;
    while(n--){
        cin>>q;
        
        if(strstr(s,q) != NULL) cout<<strstr(s,q)<<endl;
        else cout<<"Not Found"<<endl;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值