/****************************************************************************** Copyright(C) 2009 File Name : kmp.h Author : vison Email : vison0300@163.com Date : 2009-10-28 Description : KMP模式匹配算法 ******************************************************************************/ #ifndef __KMP_HEADER_FILE__ #define __KMP_HEADER_FILE__ #include <string> using namespace std; namespace str { void getnext(std::string& p, int next[]) { int i = 0; int j = -1; int szp = p.size(); next[0] = -1; while (i < szp) { if (j == -1 || p[i] == p[j]) { next[++i] = ++j; } else { j = next[j]; } } } int kmp(std::string& t, std::string& p) {//t为正文,p为模式 int i = 0; int j = 0; int szt = t.size(); int szp = p.size(); int* next = new int[szp + 1]; memset(next, 0, sizeof(int) * (szp + 1)); getnext(p, next); while (i < szt && j < szp) { if (j == -1 || t[i] == p[j]) { i++; j++; } else { j = next[j]; } } delete[] next; return (j == szp) ? (i - szp) : (-1); } }; #endif//__KMP_HEADER_FILE__ /****************************************************************************** Copyright(C) 2009 File Name : main.cpp Author : vison Email : vison0300@163.com Date : 2009-10-28 Description : 测试 ******************************************************************************/ #include <iostream> #include "kmp.h" using namespace std; int main(int argc, char* argv[]) { std::string t("visondadssonok"); std::string p("sson"); cout<<str::kmp(t, p)<<endl; while (true) { char c; cin>>c; if (c == 'q') break; } return (0); }