浙大pat1040 Longest Symmetric String(25 分)

Posted sk1997

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浙大pat1040 Longest Symmetric String(25 分)相关的知识,希望对你有一定的参考价值。

1040 Longest Symmetric String(25 分)

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


题目思路:这个题实质是求最长回文子串的长度。
有两种思路,第一种是以中间元素为中心,向两边扩散,这种写法及其好写,但是麻烦的是遇到abba这种偶数个回文串的情况就不知道怎么办了。在网上找到了一个神奇的方法,就是往每个字符串两边添加一个字符,之后再将总数除以2即可
这是该思路的链接https://blog.csdn.net/sunbaigui/article/details/8656933
贴一下我写的代码:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
	string so;
	getline(cin,so);
	int length = so.length();
	string s;
	for(int i=0;i<length;i++)
	{
		s.push_back(‘-‘);
		s.push_back(so[i]);
	}
	s.push_back(‘-‘);
	
	int max = -1;
	for(int i=1;i<s.length()-1;i++)
	{
		int tmp_length=1;
		int p,q;
		p = i-1;
		q = i+1;
		while (s[p] == s[q]) 
		{
			p--;
			q++;
			tmp_length+=2;
			if(p<0||q>s.length())
			break;
		}
		if(max<tmp_length)
			max = tmp_length;
	}
	cout<<max/2;
}

  第二种思路就是把串翻转过来,转化成求两个串最大子序列的问题(一般都有板子的)这里借鉴了(https://blog.csdn.net/zhangpiu/article/details/50733603)

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
 
using namespace std;
 
string maxSubString(string s1, string s2){
	int xlen = (int)s1.size(), ylen = (int)s2.size();
	vector<vector<int>> m(xlen, vector<int>(ylen, 0));
	int maxlen = -1, index = -1;
 
	for(int i = 0; i < xlen; ++i){
		for(int j = 0; j < ylen; ++j){
			if(s1[i] == s2[j]){
				if(i == 0 || j == 0) m[i][j] = 1;
				else m[i][j] = m[i-1][j-1] + 1;
 
				if(maxlen < m[i][j]){
					maxlen = m[i][j];
					index = i - maxlen + 1;
				}
			}
		}
	}
 
	return s1.substr(index, maxlen);
}
 
int main(){
	string s;
	getline(cin, s);
 
	string rs(s);
	reverse(begin(rs), end(rs));
 
	cout << maxSubString(s, rs).size();
 
	return 0;

  







以上是关于浙大pat1040 Longest Symmetric String(25 分)的主要内容,如果未能解决你的问题,请参考以下文章

PAT1040:Longest Symmetric String

PAT 1040 Longest Symmetric String (25)

PAT甲级——A1040 Longest Symmetric String

PAT (Advanced Level) 1040. Longest Symmetric String (25)

PAT Advanced Level 1040. Longest Symmetric String (25)

PAT1040 Longest Symmetric String (25分) 中心扩展法+动态规划