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 }
  • 相关阅读:
    java fx example
    JavaFX 2.0+ WebView /WebEngine render web page to an image
    剑指Offer面试题41(Java版):和为s的两个数字VS和为s的连续正数序列
    时间类(时间戳的各种转换成)
    Android系统各种类型的service刨根解读
    二叉树的建立基本操作(链表方式)(一)
    从头认识java-13.2 利用元组的方式返回多类型对象
    EA初步使用
    inline-block元素设置overflow:hidden属性导致相邻行内元素向下偏移
    下拉框与列表框
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11257301.html
Copyright © 2011-2022 走看看