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
这个题目首先可以想到暴力破解法,我是用动态规划做的,在时间复杂度上比暴力破解法低一个数量级,但在空间上多出了开销,典型的以空间换时间的方法 我们用dp[i, j] = 1 表示s[i]到s[j]是回文串,且有dp[i, i] = 1和if (s[i] == s[j]) dp[i, j] = dp[i + 1, j - 1],还有if (s[i] == s[i - 1]) dp[i, i - 1] = 1这个就是比如PAAT的情况,接下来就是填dp矩阵的问题了,看代码
1 |
|