题目描述: Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
读题: 找最长的回文字符串
知识储备:
动态规划(见http://blog.csdn.net/ivyusing/article/details/70432068)
Java String API
字符串转为字符数组 | public char[] toCharArray() |
字符数组转为字符串 | public String(char[] value) |
获取给定的Index处的字符 | char charAt(int index) |
返回字符串的子串 | String substring(int beginIndex, endIndex结束索引(不包括)) |
解题思路:
寻找回文字符串:
1.分解问题:回文字符串中前半部分每个字符都能在后半部分对称的位置找到与之相同的字符。
2.解决问题: 遍历一遍字符数组,找到前面与之相同的字符,如果两个字符之间的距离小于3,如aba,aa,说明是符合回文规则的,dp表上标记为true; 若两个字符之间的距离大于2,那么他们各自前面的字符也要是相同的才符合回文规则。
提交代码:
public class Solution {
public String longestPalindrome(String s) {
if(s.length() == 0) {
return "";
}
int len = s.length();
boolean[][] dpTable = new boolean[len][len];
int resLen = 0;
int head = 0;
int tail = 0;
char dst[] = s.toCharArray();
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
if(dst[i] == dst[j] && (i - j <= 2 || dpTable[j+1][i-1])) {
dpTable[j][i] = true;
}
if(dpTable[j][i] && resLen < i - j + 1) {
head = j;
tail = i;
resLen = i - j + 1;
}
}
}
return s.substring(head, tail + 1);
}
}