hdu 1867 A + B for you again

本文深入探讨了KMP算法的实现原理,并通过一个具体的题目示例——hdu1867A+B for you again,展示了如何使用KMP算法解决字符串匹配问题。文章详细解释了如何构建next数组来加速字符串匹配过程,以及如何根据匹配结果确定最优字符串连接方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hdu 1867 A + B for you again

题目没有说明输入一定是前一个字符串的后缀和后一个字符串匹配,所以需要进行两次kmp匹配,然后得出最大的匹配数。

#include <stdio.h>
#include <string.h>

#define MAX 100005

char strA[MAX], strB[MAX];
int next[MAX];

void getNext(char* str, int* next) {
	int len;
	int j, k;
	
	j = 0;
	k = -1;
	next[0] = k;
	len = strlen(str) - 1;
	
	while (j < len) {
		if (k == -1 || str[k] == str[j]) {
			++k, ++j;
			
			if (str[k] == str[j]) {
				next[j] = next[k];
			} else {
				next[j] = k;
			}
		} else {
			k = next[k];
		}
	}
}

int kmp(char* strA, char* strB) {
	int lenA, lenB;
	int i, j;
	
	i = j = 0;
	lenA = strlen(strA);
	lenB = strlen(strB);
	getNext(strB, next);
	
	if (lenA > lenB) {
		i = lenA - lenB;
	}
	
	while (i < lenA) {
		if (j == -1 || strA[i] == strB[j]) {
			++j, ++i;
		} else {
			j = next[j];
		}
	}
	
	return j;
}

int main() {
	int numA, numB, num;
	int lenA, lenB, len;
	int i;

	while (scanf("%s%s", strA, strB) != EOF) {
		numA = kmp(strA, strB);
		numB = kmp(strB, strA);
		num = numA > numB ? numA : numB;

		if (num == 0) {
			if (strcmp(strA, strB) < 0) {
				printf("%s%s\n", strA, strB);
			} else {
				printf("%s%s\n", strB, strA);
			}
		} else {
			if (numA == num) {
				printf("%s%s", strA, strB + num);
			} else {
				printf("%s%s", strB, strA + num);
			}

			printf("\n");
		}
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值