浙大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;

  

猜你喜欢

转载自www.cnblogs.com/SK1997/p/9588868.html