URAL 1354 Palindrome. Again Palindrome (回文 + KMP)

#include <stdio.h>

char string[10001];
char reverseString[10001];
int next[10001];

int main(){

	scanf("%s", string);
	int len = 0;
	int index;
	for (index = 0; string[index] != '\0'; index++){
		len++;
	}

	int reverseIndex = 0;
	for (index = len - 1; index >= 0; index--){
		reverseString[reverseIndex++] = string[index];
	}
	reverseString[reverseIndex] = '\0';

	int prefix = -1;
	int suffix = 0;
	next[suffix] = -1;
	//注意边界不是len
	while (suffix < len - 1){
		if (-1 == prefix || reverseString[prefix] == reverseString[suffix]){
			prefix++;
			suffix++;
			if (reverseString[prefix] != reverseString[suffix]){
				next[suffix] = prefix;
			} else {
				next[suffix] = next[prefix];
			}
		} else {
			prefix = next[prefix];
		}
	}

	//用KMP算法求输入字符的反串的前缀在输入字符串第1个字符之后的位置
	index = 1;
	reverseIndex = 0;
	while (index < len){
		if (string[index] == reverseString[reverseIndex] || -1 == reverseIndex){
			index++;
			reverseIndex++;
		} else {
			reverseIndex = next[reverseIndex];
		}
	}

	printf("%s", string);
	while (reverseIndex < len){
		printf("%c", reverseString[reverseIndex++]);
	}
	printf("\n");	

	return 0;
}

你可能感兴趣的:(KMP,回文,pa,again,ural,1354,Palindrome.)