Last active
February 5, 2017 03:40
-
-
Save Chen-tao/216a732c5897ccd0816595d81a570227 to your computer and use it in GitHub Desktop.
动态规划,列举回文串的起点或者终点来解最长回文串问题,无需讨论串长度的奇偶性
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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