# 1040. Longest Symmetric String (25)

504人阅读 评论(0)

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


#include <iostream>
#include <string>

using namespace std;

string str;

int isRevese(int s, int e){
int length = 1;
while(s < e){
if(str[s] != str[e]) return 1;
s++;
e--;
if(length == 1) length = 2;
else length += 2;
}

if(length != 1 && s == e) length++;

return length;

}

int main()
{
getline(cin,str);

int start_index = 0;
int end_index = str.length() - 1;
int max_length = -1;
int len = 0;

for(start_index = 0; start_index < str.length(); start_index++){
for(end_index = str.length() - 1; end_index >= start_index; end_index--){
len = isRevese(start_index,end_index);
if(len > max_length){
max_length = len;
}
}
}
cout << max_length << endl;
return 0;
}

#include<iostream>
#include<string.h>
#include<vector>

#define Max 10000
int dp[2*Max+1];
char str[Max];

int mmax(int a, int b)
{
if(a > b) return a;
else return b;
}
int main()
{
while(gets(str))
{
//memset(dp, -1, sizeof(dp));
int len = strlen(str);
//insert special character into str, must not appeared in str
std::vector<int> magic;
for(int i = 0; i < len; ++i)
{
magic.push_back(-1);//special character
magic.push_back(str[i]);//character to int
}
magic.push_back(-1);
//enumerate center point for magic vector
len = (int)magic.size();
int max = 1;
for(int i = 1; i < len; ++i)
{
int l, r;
int step = 1;
for(l = i-1, r = i+1; l >= 0 && r < len; l--, r++)
{
if(magic[l] != magic[r])
break;
step += 2;
}
max = mmax(max, step);
}

printf("%d\n", max/2);
}
return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：233885次
• 积分：4997
• 等级：
• 排名：第5612名
• 原创：289篇
• 转载：1篇
• 译文：0篇
• 评论：33条
博客专栏
 iOS开发 文章：72篇 阅读：87712