hdu2203KMP

比较赤裸的KMP,将主串延长一倍即可达到旋转匹配的效果。

/*
 * hdu2203/win.cpp
 * Created on: 2012-7-28
 * Author    : ben
 */
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int MAX_PAR_LEN = 100005;
const int MAX_TXT_LEN = 200005;
char pattern[MAX_PAR_LEN], text[MAX_TXT_LEN];
int nextval[MAX_PAR_LEN], parlen, txtlen;
void get_nextval() {
    int i = 0, j = -1;
    nextval[0] = -1;
    while (i < parlen) {
        if (j < 0 || pattern[i] == pattern[j]) {
            i++;
            j++;
            if (pattern[i] != pattern[j]) {
                nextval[i] = j;
            } else {
                nextval[i] = nextval[j];
            }
        } else {
            j = nextval[j];
        }
    }
}
int index_kmp() {
    int i, j;
    txtlen = strlen(text);
    parlen = strlen(pattern);
    get_nextval();
    i = j = 0;
    while (i < txtlen && j < parlen) {
        if (j < 0 || text[i] == pattern[j]) {
            i++;
            j++;
        } else {
            j = nextval[j];
        }
    }
    if (j == parlen) {
        return i - j;
    } else {
        return -1;
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("data.in", "r", stdin);
#endif
    while(scanf("%s%s", text, pattern) == 2) {
        int len = strlen(text);
        if((int)strlen(pattern) > len) {
            puts("no");
            continue;
        }
        memcpy(&text[len], text, len - 1);
        text[2 * len - 1] = 0;
        if(index_kmp() < 0) {
            puts("no");
        }else {
            puts("yes");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/moonbay/p/2612689.html