zoukankan      html  css  js  c++  java
  • PAT甲级——A1040 Longest Symmetric String

    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


     1 #include <iostream>
     2 #include <string>
     3 #include <algorithm>
     4 
     5 using namespace std;
     6 string str, t1, t2;
     7 int res = 1;
     8 //最普通的遍历
     9 void way1()
    10 {
    11     for (int i = 0; i < str.length(); ++i)
    12     {
    13         for (int j = str.length() - 1; j > i; --j)
    14         {
    15             t1.assign(str.begin() + i, str.begin() + j + 1);
    16             t2.assign(t1.rbegin(), t1.rend());
    17             if (t1 == t2)
    18                 res = res > t1.length() ? res : t1.length();
    19         }
    20     }
    21 }
    22 
    23 //利用回文子串中心的两边相同
    24 void way2()
    25 {
    26     for (int i = 0; i < str.size(); ++i) {
    27         int j;
    28         for (j = 1; i - j >= 0 && i + j < str.size() && str[i + j] == str[i - j]; ++j);//以当前字符为回文中心查找最长回文子串
    29         res= max(res, 2 * j - 1);//更新回文子串最大长度
    30         for (j = 0; i - j >= 0 && i + j + 1 < str.size() && str[i - j] == str[i + 1 + j]; ++j);//以当前字符为回文中心左侧字符查找最长回文子串
    31         res = max(res, 2 * j);//更新回文子串最大长度
    32     }
    33 }
    34 
    35 //使用动态规划
    36 void way3()
    37 {
    38     int dp[1010][1010];
    39     for (int i = 0; i < str.length(); i++)
    40     {
    41         dp[i][i] = 1;
    42         if (i < str.length() - 1 && str[i] == str[i + 1])
    43         {
    44             dp[i][i + 1] = 1;
    45             res = 2;
    46         }
    47     }
    48     for (int L = 3; L <= str.length(); L++) {
    49         for (int i = 0; i + L - 1 < str.length(); i++) {
    50             int j = i + L - 1;
    51             if (str[i] == str[j] && dp[i + 1][j - 1] == 1) {
    52                 dp[i][j] = 1;
    53                 res = L;
    54             }
    55         }
    56     }
    57 }
    58 
    59 int main()
    60 {
    61     getline(cin, str);
    62     way1();
    63     cout << res << endl;
    64     return 0;
    65 }
  • 相关阅读:
    ORACLE的客户端、后台进程
    第一范式、第二范式、第三范式
    在VMware Workstation10下CentOS7虚拟机中创建与主机共享文件夹的详细步骤
    oracle经典查询语句
    vmware 安装XP 32位Professional版本
    增、删、改、查
    Windows/Linux服务器/Git/svn/get和post
    三大原理(计算机原理、操作系统原理、编译原理)两个协议(TCP与HTTP协议)一种结构(数据结构)
    EF删除,查询,Linq查询,Lambda查询,修改链接字符串
    EF添加和修改
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11257301.html
Copyright © 2011-2022 走看看