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;
}

  

posted @ 2017-11-01 23:17  0kk470  阅读(212)  评论(0编辑  收藏  举报