ABB(回文字符串)

训练赛上过的一道题,记录在这里,以下是题面:

Fernando was hired by the University of Waterloo to finish a development project the university started some time ago. Outside the campus, the university wanted to build its representative bungalow street for important foreign visitors and collaborators.

Currently, the street is built only partially, it begins at the lake shore and continues into the forests, where it currently ends. Fernando’s task is to complete the street at its forest end by building more bungalows there. All existing bungalows stand on one side of the street and the new ones should be built on the same side. The bungalows are of various types and painted invarious colors.

The whole disposition of the street looks a bit chaotic to Fernando. He is afraid that it will look even more chaotic when he adds new bungalows of his own design. To counter balance the chaosof all bungalow shapes, he wants to add some order to the arrangement by choosing suitablecolors for the new bungalows. When the project is finished, the whole sequence of bungalowcolors will be symmetric, that is, the sequence of colors is the same when observed from eitherend of the street.

Among other questions, Fernando wonders what is the minimum number of new bungalows heneeds to build and paint appropriately to complete the project while respecting his self-imposed bungalow color constraint.

Input Specification

The first line contains one integer N(1≤N≤4⋅105)N (1 \leq N \leq 4·10^{5})N(1≤N≤4⋅105), the number of existing bungalows in the street. The next line describes the sequence of colors of the existing bungalows, from the beginning of the street at the lake. The line contains one string composed of N lowercase letters(“a” through “z”), where different letters represent different colors.

Output Specification

Output the minimum number of bungalows which must be added to the forest end of the street and painted appropriately to satisfy Fernando’s color symmetry demand.
样例输入1

3
abb

样例输出1

1

样例输入2

12
recakjenecep

样例输出2

11

大致题意:

求在给出的字符串后面最少添加多少个字符可以让整个字符串变成一个回文字符串。

大致思路:

寻找原字符串中最长的并且包含最后一个字符的回文字符串,找到后即得到答案。本题我使用了一个二维vector,用来在输入的时候储存每个字母都在哪个位置出现过,然后写了个函数,参数为字母的位置,用来判断从参数给出的位置开始一直到最后形成的这个字符串是不是回文的。因为一定要包含最后一个字母,所以在输入结束之后直接遍历最后一个字母所在的vector,看看在哪个位置出现的那个字母能够和最后一个字母构成一个回文串。

AC代码:

#include 
using namespace std;
char s[400005];
int n;
bool F(int a)
{
    for(int i=a,j=n-1;i<=j;i++,j--)if(s[i]!=s[j])return false;
    return true;
}
int main()
{
    cin>>n;getchar();
    vectorcheck[26];
    for(int i=0;i

你可能感兴趣的:(个人题解,字符串)