1040. Longest Symmetric String (25)-PAT甲级真题(动态规划)

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][j]表示s[i]到s[j]所表示的字串是否是回文字串。只有0和1,递推方程为: 

1 当s[i] == s[j] : dp[i][j] = dp[i+1][j-1]

2 当s[i] != s[j] : dp[i][j] =0

3 边界:dp[i][i] = 1, dp[i][i+1] = (s[i] == s[i+1]) ? 1 : 0因为i、j如果从小到大的顺序来枚举的话,无法保证更新dp[i][j]的时候dp[i+1][j-1]已经被计算过。因此不妨考虑按照字串的长度和子串的初试位置进行枚举,即第一遍将长度为3的子串的dp的值全部求出,第二遍通过第一遍结果计算出长度为4的子串的dp的值…这样就可以避免状态无法转移的问题

首先初始化dp[i][i] = 1, dp[i][i+1],把长度为1和2的都初始化好,然后从L = 3开始一直到 L <= len 根据动态规划的递归方程来判断

❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼

❤ 点击这里 -> 订阅《从放弃C语言到使用C++刷算法的简明教程》by 柳婼

❤ 点击这里 -> 订阅PAT甲级乙级、蓝桥杯、GPLT天梯赛、LeetCode题解离线版