字符串模式匹配的KMP算法实现

方法一:朴素模式匹配

思路:遍历主串,匹配失败则模式串右移1位,重新从头开始匹配

#include<iostream>
#include<string>
using namespace std;
//字符串模式匹配(返回第一次匹配的下标)
//朴素算法

//s为主串 
int index(string s, string ss)
{
	//长串为主串
	if(s.size() < ss.size()) {
		string tmp = s;
		s = ss;
		ss = tmp;
	} 
	int i(0), j(0), flag(0);
	while(i <= s.size() - ss.size()  && !flag) {
		j = 0;
		flag = 1;
		while(j < ss.size() && flag) {
			if(ss[j] == s[i + j])++ j;
			else flag = 0;
		}
		++ i;
	}
	return flag ? (i - 1) : -1;
}
 
int main()
{
	string s(""), ss("");
	while(cin >> s >> ss) {
		cout << index(s, ss) << endl; 
	}
	return 0;
}

方法二:KMP算法实现

KMP的思路和理解,借鉴几篇博客:

http://www.matrix67.com/blog/archives/115

http://kenby.iteye.com/blog/1025599

下面是我的代码:

#include<iostream>
#define MAXN 11111
using namespace std;
//s为主串 
void change(string *s, string *ss)
{
	if((*s).size() < (*ss).size()) {
		string tmp = *ss;
		*ss = *s;
		*s = tmp;
	}
}
void get_next(string ss, int next[])
{	
	int len = ss.size();
	int i = 0, j = -1;
	next[0] = -1;
	while(i < len) {
		if(j == -1 || ss[i] == ss[j]) {
			next[ ++ i ] = (++ j);
		}else {
			j = next[j];
		}
	}
}

int kmp(string s, string ss, int next[])
{
	int s_len = s.size(), ss_len = ss.size();
	int i(0), j(0);
	while(i < s_len && j < ss_len) {
		if(j == -1 || s[i] == ss[j]) {
			++ i; ++ j;
		}else {
			j = next[j];
		}
	}
	if(j == ss_len) return (i - ss_len);
	return -1;
}
int main()
{
	//s为主串 
	string s(""), ss("");
	int next[MAXN];
	while(cin >> s >> ss) {
		change(&s, &ss);
		get_next(ss, next);
		cout << kmp(s, ss, next) << endl; 
	}
	return 0;
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/qq_24336085/article/details/71599103
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞