1040 Longest Symmetric String (25分)(dp)

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[i]=前i个字符中最大的对称字串$

$dp[i]=egin{cases}dp[i]=max(dp[i],dp[i-1]+2),& ext{if} s[i-1]=s[i-dp[i-1]-2] \ dp[i]=max(dp[i],dp[i-1]+1), & ext{if} s[i-1]=s[i-dp[i-1]-1] end{cases}$

$估计这也并不好理解  其实可以这么想 对于每一个dp[i]来说 我们更新它只有两种方式,一种是在dp[i-1]的基础上加两个字符 分别是 第i-1个字符与 i-dp[i-1]-2字符(不难算)  一种是在dp[i-1]的基础上只加第i-1个元素$

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <climits>
 3 #include<iostream>
 4 #include<vector>
 5 #include<queue>
 6 #include<map>
 7 #include<set>
 8 #include<stack>
 9 #include<algorithm>
10 #include<string>
11 #include<cmath>
12 using namespace std;
13 int dp[1010]; //dp[i]定义为前i个字符中最大对称字串
14 
15 int main()
16 {
17     string s;
18     getline(cin, s);
19     for (int i = 1; i <= s.length(); i++)
20     {
21         if (i - dp[i - 1] - 2 >= 0)
22             if (s[i - 1] == s[i - dp[i - 1] - 2])
23                 dp[i] =max(dp[i],dp[i - 1] + 2);
24         if (i - dp[i - 1] - 1 >= 0)
25             if (s[i - 1] == s[i - dp[i - 1] - 1])
26                 dp[i] = max(dp[i], dp[i - 1] + 1);
27         dp[i] = max(dp[i], 1);
28     }
29     int max = -65535;
30     for (int i = 0; i <= s.length(); i++)
31     {
32         if (dp[i] > max)
33             max = dp[i];
34     }    
35     cout << max;
36 }
View Code
原文地址:https://www.cnblogs.com/57one/p/12019246.html