1040 Longest Symmetric String (25分)(dp)
2024-09-05 01:08:18
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]=\begin{cases}dp[i]=max(dp[i],dp[i-1]+2),& \text{if}\ s[i-1]=s[i-dp[i-1]-2] \\ dp[i]=max(dp[i],dp[i-1]+1), & \text{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个元素$
#define _CRT_SECURE_NO_WARNINGS
#include <climits>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int dp[]; //dp[i]定义为前i个字符中最大对称字串 int main()
{
string s;
getline(cin, s);
for (int i = ; i <= s.length(); i++)
{
if (i - dp[i - ] - >= )
if (s[i - ] == s[i - dp[i - ] - ])
dp[i] =max(dp[i],dp[i - ] + );
if (i - dp[i - ] - >= )
if (s[i - ] == s[i - dp[i - ] - ])
dp[i] = max(dp[i], dp[i - ] + );
dp[i] = max(dp[i], );
}
int max = -;
for (int i = ; i <= s.length(); i++)
{
if (dp[i] > max)
max = dp[i];
}
cout << max;
}
最新文章
- Hbase+ Phoenix搭建教程
- Extended TCP/IP Stack In Linux: Netfilter Hooks and IP Table
- websocket实例(显示文件导入处理进度)
- C++中的内联成员函数与非内联成员函数
- Fresco源码解析 - 创建一个ImagePipeline(一)
- dom 优酷得弹出
- HTML增加删除邮件(table)
- 一周一话题之三(Windows服务、批处理项目实战)
- Truncate Table 用法
- mysql select不使用任何锁(select with nolock)
- A Game of Thrones(17) - Bran
- 作为一个.net程序猿,需要掌握这些有点前途的人才,一些开发---Shinepans
- InnoDB关键特性之change buffer
- ABP入门系列(21)——切换MySQL数据库
- 使用eclipse开发工具与hibernate开发者为开源一起做贡献
- 从0开始的Python学习002python的数据类型
- Windows应用程序组成及编程步骤
- py001
- IFS简单说明
- Confluence 6 识别系统属性