publicStringlongestPalindrome(String s) {if (s ==null||s.isEmpty()) {return""; }String longest ="";for (int i =0; i <s.length(); i++) {String oddParStr =getLongestParFrom(s, i, i);if (oddParStr.length() >longest.length()) { longest = oddParStr; }String evenParStr =getLongestParFrom(s, i, i +1);if (evenParStr.length() >longest.length()) { longest = evenParStr; } }return longest;}privateStringgetLongestParFrom(String str,int left,int right) {while (left >=0&& right <str.length()) {if (str.charAt(left) !=str.charAt(right)) {break; } left--; right++; }returnstr.substring(left +1, right);}
可以用九章的dp,也可以用不知道是谁写的dp。
一步到位的dp:
publicStringlongestPalindrome(String s) {if (s ==null||s.isEmpty()) {return""; }int n =s.length();boolean[][] isPal =newboolean[n][n];int maxLen =0;String res ="";for (int i =0; i < n; i++) {for (int j =0; j <= i; j++) {// i - j <= 1, same char or next to each other isPal[i][j] =s.charAt(i) ==s.charAt(j) && (i - j <=1|| isPal[i -1][j +1]); if (isPal[i][j] && maxLen < i - j +1) { maxLen = i - j +1; res =s.substring(j, i +1); } } }return res;}
分步填的dp:
publicStringlongestPalindrome(String s) {if (s ==null||s.length() ==0) {return""; }int len =s.length();boolean[][] isPar =newboolean[len][len];calParMatrix(isPar, s);int max =0;String res ="";for (int i =0; i < len; i++) {for (int j = i; j < len; j++) {if (isPar[i][j]) {int cur = j - i +1;if (max < cur) { max = cur; res =s.substring(i, j +1); } } } }return res;}privatevoidcalParMatrix(boolean[][] isPar,String s) {int len =isPar.length;// diagonal are all truefor (int i =0; i < len; i++) { isPar[i][i] =true; }// chars next to each otherfor (int i =0; i < len -1; i++) { isPar[i][i +1] = (s.charAt(i) ==s.charAt(i +1)); }// find the restfor (int l =2; l < len; l++) {for (int start =0; start + l < len; start++) { isPar[start][start + l] =s.charAt(start) ==s.charAt(start + l) && isPar[start +1][start + l -1]; } }}