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
题目大意:
求字符串的最大回文子串(LPS )。
解题思路:
假设字符串“DADBDAF”长度为7,则开一个 dp[7][7] 的Boolean类型数组,如图:
设最长子串为s,s的开始索引为i,结束索引为j,则s长度为 len = j - i + 1 ,当s长度小于2时,即只有本身字符和只有两个字符时,只要s[i] == s[j] ,便为回文。表示到dp中为:
当s长度大于2时,当之前已经是回文,只要保证新添加的两字符相等,便可保证还是回文。
即: s[i] == s[j] ,且 s[i + 1][j - 1] == true,(子串沿对角线对称),填充为:
可以看出,当某一值为true时,其左下对角线一定也为true(回文串子串)。所以填充时要自下向上,从左到右填充。
java代码:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String str = getLength(s);
// System.out.println(str);
System.out.println(str.length());
}
public static String getLength(String s) {
int len = s.length();
char[] str = s.toCharArray();
boolean [][]dp = new boolean[len][len];
int index = 0;
int max = 1;
for(int i = len - 1;i >= 0;i--) {
for(int j = i;j < len;j++) {
int l = j - i + 1;
dp[i][j] = (str[i] == str[j] && (l <= 2 || dp[i + 1][j - 1]));
if(l > max && dp[i][j]) {//当此时是回文串且长度比max大时,需要更新
index = i;//保存开始索引
max = l;
}
}
}
return s.substring(index, (index + max));
}
}