KMP示例程序

June 3, 2013
KMP

输入:   数字N,然后是N组数据,每一组数据第一行是模式串p,第二行是一个大的字符创s,如果在s里面出现了p,那么输出p第一次出现的位置,否则输出No  


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
char p[1000], s[1000];
int next[1000];
void getnext() {
  int i = 0, j = -1, len = strlen(p);
  next[0] = -1;
  while (i < len - 1) {
    if (j == -1 || p[j] == p[i]) {
      j++; i++; next[i] = j;
    }
    else j = next[j];
  }
}
int kmp() {
  int i = -1, j = -1, lenp = strlen(p), lens = strlen(s);
  getnext();
  while (j != lenp && i < lens) {
    if (j == -1 || s[i] == p[j]) {++i; ++j;}
    else j = next[j];
  }
  if (j == lenp) return i - j;
  else return -1;
}
int main(void) {
#ifndef ONLINE_JUDGE
  freopen("kmp.in", "r", stdin);
#endif
  int n;
  while (~scanf("%d", &n)) 
  while (n--){
    scanf("%s%s", p, s);
    if (kmp() == -1) {
      printf("No\n");
    } else printf("%d\n", kmp());
  }

  return 0;
}

  KMP好神奇,不愧是高老大!    

comments powered by Disqus