题目

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

1
Is PAT&TAP symmetric?

Sample Output:

1
11

思路

寻找字符串的对称部分,类似于回文数,但字符串的优势在于可以随时访问任意位置的字符,因此实现起来更简单。

注意:对称部分有可能是奇数个,也可能是偶数个,要考虑全面。

代码

Github最新代码,欢迎交流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <string.h>

int main()
{
	int maxlen = 0, l, L;
	char string[1002];

	fgets(string, 1001, stdin);

	L = strlen(string);
	for (int i = 0; i < L; i++) {
		/* odd symmetric */
		l = 0;
		while (i - l >= 0 && i + l < L && string[i - l] == string[i + l])
			l++;
		maxlen = (l * 2 - 1) > maxlen ? (l * 2 - 1) : maxlen;
		/* even symmetric */
		l = 0;
		while (i - l >= 0 && i + l + 1 < L && string[i - l] == string[i + l + 1])
			l++;
		maxlen = (l * 2) > maxlen ? (l * 2) : maxlen;
	}

	printf("%d", maxlen);
	return 0;
}