KMP算法例题

KMP算法

因为之前已写过KMP算法的总结,在这里就不介绍KMP算法了。借鉴的博客为KMP算法理解

例题一:Youhane Assembler

题目描述

详细描述见此链接

题目分析

本题大意是给出两个字符串s1,s2,要求求出最长公共s1的后缀和s2的前缀。本题主要是运用KMP的思想。将两个字符串链接起来,并且在他们中间加一个’#'作为分隔标志。这样只要求出Next数组,即可求出最长公共前后缀。

AC代码
/*
author:Manson
date:2019.2.26
theme:
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int N = 3e5+5;
string str[N];
int Next[N];
string S;
int len;
void getNext(string S){
	int i = 0,j = -1;
	Next[0] = -1;
	while(i <len){
		if(j == -1 || S[i] == S[j]){
			i++;
			j++;
			Next[i] = j;
		}
		else{
			j = Next[j];
		}
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	int n;
	cin>>n;
	for(int i = 0;i < n;i++){
		cin>>str[i];
	}
	int q;
	cin>>q;
	for(int i = 0;i < q;i++){
		int l,r;
		cin>>l>>r;
		S = str[r-1]+"#"+str[l-1];
		len = S.size();
		if(l == r){
			cout<<str[l-1].size()<<endl;
		}
		else{
			getNext(S);
			cout<<Next[len]<<endl;
		}
	}
	return 0;
}

例题二:子串

问题描述

链接地址

给出一个正整数n,我们把1…n在k进制下的表示连起来记为s(n,k),例如s(16,16)=123456789ABCDEF10, s(5,2)=11011100101。现在对于给定的n和字符串t,我们想知道是否存在一个k(2 ≤ k ≤ 16),使得t是s(n,k)的子串。

问题分析

对于本题,我们首先要对进制遍历将1到n的数字转化成为一个长字符串。然后使用kmp算法将模式串与长字符串进行匹配即可。

AC代码
/*
author:Manson
date:2019.2.26
theme:
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int N = 1e6+5;

char s1[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

int n;
string s,str;
int Next[N];
char tmp[N]; 
//k为进制 
string toString(int k,int num){
	string s = "";
	int cnt = 0;
	while(num){
		tmp[cnt] = s1[num%k];
		num /= k;
		cnt++;
	}
	for(int i = cnt-1;i >= 0;i--){
		s += tmp[i];
	}
	return s;
}

void getNext(){
	int i = 0,j = -1,len = s.size();
	while(i < len){
		if(j == -1 || s[i] == s[j]){
			i++;
			j++;
			Next[i] = j;
		}
		else{
			j = Next[j];
		}
	}
}

int kmp(){
	int i = 0,j = 0,len1 = str.size(),len2 = s.size();
	while(i < len1 && j <len2){
		if(j == -1||str[i] == s[j]){
			i++;
			j++;
		}
		else{
			j = Next[j];
		}
	}
	if(j == len2){
		return 1;
	}
	return 0;
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n>>s;
	Next[0] = -1;
	getNext();
	//遍历进制转换 
	for(int i = 2;i <= 16;i++){
		str = "";
		//从1到n遍历 
		for(int j = 1;j <= n;j++){
			str += toString(i,j);
		}
		int ans = kmp();
		if(ans == 1){
			cout<<"yes"<<endl;
			return 0;
		}
	}
	cout<<"no"<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值