zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    2020年全国安全生产月活动主题、挂图、招贴、标语、宣教用书等系列产品
    2020年安全生产月主题挂图指定宣教用品目录
    LNMP分离式部署步骤详解
    FTP文件传输服务
    DNS域名解析服务配置与测试
    DHCP服务搭建测试流程
    mysql数据库的操作
    mysql源码编译安装及其配置
    生产环境中ansible的安全处理
    http网页返回码详解
  • 原文地址:https://www.cnblogs.com/0kk470/p/7769065.html
Copyright © 2011-2022 走看看