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

      

  • 相关阅读:
    PAT1118:Birds in Forest
    PAT1112:Stucked Keyboard
    PAT1091:Acute Stroke
    Java基础006 --- 类、接口、对象
    Java基础005 --- 安全管理器、可变参数等
    Java基础004 --- BigInteger和BigDecimal
    Java基础003 --- 原始数据类型
    maven完整学习笔记(2)--- 依赖范围和依赖传递
    maven完整学习笔记(1)--- 基本概念及基础命令
    Java编译器007---javac 其它选项
  • 原文地址:https://www.cnblogs.com/0kk470/p/7769065.html
Copyright © 2011-2022 走看看