PAT甲级 -- 1040 Longest Symmetric String (25 分)

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. 动态规划里面的最长回文子串题,在胡凡的算法笔记里面类型很清楚

2. 二维dp【i】【j】表示从 str【i】到 str【j】是否是回文子串,要么是要么不是(用0 1 表示)

3.  dp【i】【j】根据 str【i】和 str【j】是否相等来转移:

(1) str【i】== str【j】,只要 str【i+1】到 str【j-1】是回文串,那么 str【i】到 str【j】也是回文串

(2)str【i】!= str【j,str【i】到 str【j】,肯定不是回文串

4. 边界条件: dp【i】【i】 = 1, dp【i】【i+1】= ( s【i】== s【i+1】)? 1:0

5. 按 i j 从大到小枚举无法保证dp【i+1】【j-1】已经求解,采取枚举子串长度L,再枚举左端点,右端点可知,进行求解

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 1010;
char str[MAXN];
int dp[MAXN][MAXN];

int main() {
	cin.getline(str,MAXN);
	fill(dp[0], dp[0]+MAXN*MAXN, 0);
	int len = strlen(str), ans = 1;
	for(int i = 0;  i < len; i++){ //初始化
		dp[i][i] = 1;
		if(i < len-1){
			if(str[i] == str[i+1]){
				dp[i][i+1] = 1;
				ans = 2;
			}
		}
	}
	for(int L = 3; L <= len; L++){
		for(int i = 0; i+L-1 < len; i++){
			int j = i+L-1;
			if(str[i] == str[j] && dp[i+1][j-1] == 1){  //相等并且str[i+1]到str[j-1]也是回文串
				dp[i][j] = 1;
				ans = L;
			}
		}
	}
	printf("%d", ans);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值