1040. Longest Symmetric String-PAT 1528:最长回文子串-九度

1040. Longest Symmetric String (25)

时间限制
400 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
Is PAT&TAP symmetric?
Sample Output:
11
推荐指数:※※
这一道题,首先考虑使用动态规划,但http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html的O(N)算法极其巧妙。
下面的代码就是仿照它写的:
#include <iostream>
using namespace std;
#define N 1004
#define min(a,b) ((a)<(b)?(a):(b))
int find_longest_symmetric(char str[])
{
	int i,j,center,max;
	int p[N];
	char scp[2*N];
	i=0,j=0;
	scp[j++]='#';
	while(str[i]!='\0'){
		scp[j++]=str[i++];
		scp[j++]='#';
	}
	scp[j]='\0';
	for(i=0;i<N;i++)
		p[i]=0;
	i=1;
	center=0;
	while(scp[i]!='\0'){
		p[i]=(center+p[center])>i?min(p[center-(i-center)],center+p[center]-i):0;
		while(scp[i+p[i]+1]==scp[i-p[i]-1]&&(i-p[i]-1)>=0)
			p[i]++;
		if(i+p[i]>center)
			center=i;
		i++;
	}
	max=0;
	i--;
	while(i>=0){
		if(p[i]>max)
			max=p[i];
		i--;
	}
	return max;
}

int main()
{
	char str[N];
	cin.getline(str,N);
	cout<<find_longest_symmetric(str)<<endl;
	return 0;
	
}
九度在空间使用上面要注意一下:
   
   
   
   
题目描述:

回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。 回文子串,顾名思义,即字符串中满足回文性质的子串。 给出一个只由小写英文字符a,b,c...x,y,z组成的字符串,请输出其中最长的回文子串的长度。

输入:

输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于200000。

输出:

对于每组测试用例,输出一个整数,表示该组测试用例的字符串中所包含的的最长回文子串的长度。

样例输入:
abab
bbbb
abba
样例输出:
3
4
4
#include <iostream>
#include<string.h>
using namespace std;
#define N 200002
#define min(a,b) ((a)<(b)?(a):(b))
int find_longest_symmetric(char str[])
{
	int i,j,center,max;
	//int p[N];
	int size_p=2*strlen(str)+2;
	int *p=new int[size_p];
	char *scp=new char[size_p];
	i=0,j=0;
	scp[j++]='#';
	while(str[i]!='\0'){
		scp[j++]=str[i++];
		scp[j++]='#';
	}
	scp[j]='\0';
	for(i=0;i<size_p;i++)
		p[i]=0;
	i=1;
	center=0;
	while(scp[i]!='\0'){
		p[i]=(center+p[center])>i?min(p[center-(i-center)],center+p[center]-i):0;
		while(scp[i+p[i]+1]==scp[i-p[i]-1]&&(i-p[i]-1)>=0)
			p[i]++;
		if(i+p[i]>center)
			center=i;
		i++;
	}
	max=0;
	i--;
	while(i>=0){
		if(p[i]>max)
			max=p[i];
		i--;
	}
	delete(p);
	delete(scp);
	return max;
}

int main()
{
	char *str=new char[N];
	while(cin>>str){
		cout<<find_longest_symmetric(str)<<endl;
	}
	return 0;
	
}


你可能感兴趣的:(1040. Longest Symmetric String-PAT 1528:最长回文子串-九度)