5最长回文子串
作者:互联网
与前两篇博客,最长回文子序列有点像
都是先求出长度为1,长度为2,长度为3.。。长度为n的子串是否为回文
然后动态规划
if(j + 1 < i + j - 1 && !dp[j+1][i+j-1]){
这一句是如果有些是偶数的话 比如“bb”子串,要判断一下
程序
class Solution { public String longestPalindrome(String s) { if (s.length() == 0 || s == null) { return ""; } int length = s.length(); char[] str = s.toCharArray(); boolean[][] dp = new boolean[length][length]; for (int i = 0; i < length; i++) { dp[i][i] = true; } int max = 1; String maxStr = s.substring(0,1); for (int i = 1; i < length; ++i) { for (int j = 0; j + i < length; ++j) { if (str[j] == str[i + j]) { if(j + 1 < i + j - 1 && !dp[j+1][i+j-1]){ dp[j][i+j] = false; }else{ dp[j][i+j] = true; max = Math.max(max,i + 1); maxStr = s.substring(j,i+j+1); } } } } return maxStr; } }
标签:子串,String,int,max,maxStr,length,最长,dp,回文 来源: https://www.cnblogs.com/da-peng/p/11794010.html