题目:给定一个字符串找出其中最短的回文子字符串
这个题目暴力求解的话很简单就是直接找出所有回文子串,然后比较长度,但是是O(3)的复杂度。
class Solution {
public int longestPalindromeSubseq(String s) {
// (1) 找子序列
// (2) 判断该子序列是否为回文
// (3) 回文最长的长度
// (4) 采用从后向前搜索的方式,定义count[i][j]为字符串从i到j这段中最长的回文长度
// 1. 如果头尾相等,那么就会往中间收缩
// 2. 如果头尾不想等,那么count[i][j]的长度就应该是上一步计算好的即count[i+1][j],count[i][j-1]中的某一个
// 3. 然后扩大搜索范围,直到遍历完全部字符
int[][] count = new int[s.length()][s.length()];
for(int i = s.length() - 1;i >= 0;i--){
count[i][i] = 1;
for(int j = i+1;j < s.length();j++){
// 从中心扩散,所以count[i + 1][j - 1]一定是回文的长度
if(s.charAt(i) == s.charAt(j)){
count[i][j] = count[i + 1][j - 1] + 2;
}else{
count[i][j] = Math.max(count[i + 1][j],count[i][j - 1]);
}
}
}
return count[0][s.length() - 1];
}
}