1. 程式人生 > >PAT1040:Longest Symmetric String

PAT1040:Longest Symmetric String

ges 情況 限制 最長回文子串 是否 maximum 根據 數組 -1

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