Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Last active February 5, 2017 03:40
Show Gist options
  • Save Chen-tao/216a732c5897ccd0816595d81a570227 to your computer and use it in GitHub Desktop.
Save Chen-tao/216a732c5897ccd0816595d81a570227 to your computer and use it in GitHub Desktop.
动态规划,列举回文串的起点或者终点来解最长回文串问题,无需讨论串长度的奇偶性
public int longestPalindrome(String s) {
int n=s.length();
boolean[][] pal=new boolean[n][n];
//pal[i][j] 表示s[i...j]是否是回文串
int maxLen=0;
for (int i=0;i<n;i++){ // i作为终点
int j=i; //j作为起点
while (j>=0){
if (s.charAt(j)==s.charAt(i)&&(i-j<2||pal[j+1][i-1])){
pal[j][i]=true;
maxLen=Math.max(maxLen, i-j+1);
}
j--;
}
}
return maxLen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment