---
title: "KMP模式匹配算法 C++实现"
author: "pleasetojava"
date: "2011-11-16T16:46:00Z"
tags: []
slug: "kmp-c"
draft: false
lastmod: "2011-11-21T09:58:18Z"
id: 1270376
url: "https://pleasetojava.iteye.com/blog/1270376"
---

**KMP模式比配算法**

**// KMP模式比配算法.cpp : Defines the entry point for the console application.**  
**//**

**#include "stdafx.h"**  
**#include&lt;iostream&gt;**  
**#define MAX 1000**  
**using namespace std;**

**char s\[MAX],t\[MAX];**  
**int next\[MAX];**

**//**  
**void ComputeNext(char \*t,int \*next,const int lenT)**  
**{**  
**int i,j;**  
**next\[0] = -1;**  
**i = 0;**  
**j = -1;**  
**while(i&lt;lenT)**  
**{**  
**while(j&gt;=0&&t\[i] !=t\[j] )**  
**j = next\[j];**  
**j++;**  
**i++;**  
**//next\[i] = j;**  
**//改进**  
**if(t\[i]==t\[j])**  
**next\[i] = next\[j];**  
**else**  
**next\[i] = j;**  
**}**  
**}**

**//**  
**int KMP(char \*s,char \*t,int \*next,const int lenS,const int lenT)**  
**{**  
**int i,j;**  
**i=j=-1;**  
**while(i&lt;lenS&&j&lt;lenT)**  
**{**  
**if((j==-1)||(s\[i]==t\[j]))**  
**{**  
**i++;**  
**j++;**  
**}**  
**else**  
**j = next\[j];**  
**}**  
**if(j&gt;=lenT)**  
**return i-lenT+1;**  
**else**  
**return 0;**  
**}**

**int \_tmain(int argc, \_TCHAR* argv\[])**  
**{**  
**int cases;**  
**cout&lt;&lt;"请输入案例的个数：";**  
**cin&gt;&gt;cases;**  
**while(cases--)**  
**{**  
**cout&lt;&lt;"请输入主串:"&lt;&lt;endl;**  
**cin&gt;&gt;s;**  
**int lenS = strlen(s);**  
**while(1)**  
**{**  
**cout&lt;&lt;"请输入需要匹配的模式串(以0结束):"&lt;&lt;endl;**  
**cin&gt;&gt;t;**  
**if(!strcmp(t,"0"))**  
**break;**  
**int lenT = strlen(t);**  
**for(int i=0;i&lt;lenT;i++)**  
**next\[i] = -1;**  
**ComputeNext(t,next,lenT);**  
**int pos = KMP(s,t,next,lenS,lenT);**  
**if(pos==0)**  
**cout&lt;&lt;"没有匹配项!"&lt;&lt;endl;**  
**else**  
**cout&lt;&lt;"匹配的开始位置为:"&lt;&lt;pos&lt;&lt;endl;**  
**}**  
**}**  
**system("pause");**  
**return 0;**  
**}**

**---------------------------------------------------程序测试---------------------------------------------------**

**请输入案例的个数：1**  
**请输入主串:**  
**heyongluoyao8**  
**请输入需要匹配的模式串(以0结束):**  
**he**  
**匹配的开始位置为:1**  
**请输入需要匹配的模式串(以0结束):**  
**yong**  
**匹配的开始位置为:3**  
**请输入需要匹配的模式串(以0结束):**  
**luo**  
**匹配的开始位置为:7**  
**请输入需要匹配的模式串(以0结束):**  
**luoyao**  
**匹配的开始位置为:7**  
**请输入需要匹配的模式串(以0结束):**  
**lao**  
**没有匹配项!**  
**请输入需要匹配的模式串(以0结束):**  
**0**  
**请按任意键继续. . .**