PAT1040:Longest Symmetric String

Posted 0kk470

tags:

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

1040. Longest Symmetric String (25)

时间限制
400 ms
内存限制
65536 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


思路

求一个字符串的最长回文子串。

DP的思想,复杂度O(n^2)。
1.如果一个从i到j的字符串str(i,j)的子串str(i+1,j-1)为回文串,那么在str[i] == str[j]的情况下,字符串str(i,j)也是回文串。
2.每一个字符本身就是一个回文串。所以在每一个字符的基础上,根据1的条件来确定更长的回文串。
3.用一个bool数组isSym[1001][1001]来列举所有的情况,isSym[i][j]表示起始位置为i、终止位置为j的字符串是否是回文串。
4.检查是否有N个长度的回文串,更新最大长度maxlength。(1 <=N <= str.length())。

代码
#include<iostream>
#include<vector>
using namespace std;
vector<vector<bool>> isSym(1001,vector<bool>(1001,false));
int main()
{
    string s;
    getline(cin,s);
    int maxlength = 1;
    const int Length = s.size();
    for(int i = 0;i < Length;i++)
    {
        isSym[i][i] = true;
        if(i < Length - 1 && s[i] == s[i + 1])
        {
            isSym[i][i+1] = true;
            maxlength = 2;
        }
    }

    for(int len = 3;len <= Length;len++)
    {
        for(int i = 0;i <= Length - len;i++)
        {
            int j = i + len - 1;
            if(isSym[i+1][j-1] && s[i] == s[j])
            {
                   isSym[i][j] = true;
                   maxlength = len;
            }
        }
    }
    cout << maxlength << endl;
}

  

以上是关于PAT1040:Longest Symmetric String的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1040 Longest Symmetric String (25)

浙大pat1040 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分) 中心扩展法+动态规划