public class LongestPalindrome { // 暴力算法 public String longestPalindrome(String s) { if (s == null) return null; if (s.length() <= 1) return s; String sub = null; int len = 0; for (int i = 0; i < s.length(); i++)
{ for (int j = i; j < s.length(); j++)
{ String tmp = s.substring(i, j + 1); if (isPalindrome(tmp) && tmp.length() > len)
{ sub = tmp; len = tmp.length(); } } } return sub; } public boolean isPalindrome2(String s) { int len = s.length(); if (len % 2 == 1) { // 这样写是很愚蠢的。因为既然知道了i是可以用总长度-i得到j,而不是让i和j同时滑动。 for (int i = 0, j = len - 1; i < len / 2 && j > len / 2; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; } else { for (int i = 0, j = len - 1; i < len / 2 && j > len / 2; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; } } public boolean isPalindrome(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true; } // 动态规划算法 public String longestPalindrome1(String s) { if (s == null) return null; if (s.length() <= 1) return s; int maxLen = 0; String longestStr = null; int length = s.length(); int[][] table = new int[length][length]; // 单个字符是回文字符串 for (int i = 0; i < length; i++) { table[i][i] = 1; maxLen = 1; } // 两个相同字符也是回文字符串 for (int i = 0; i < length - 1; i++) { if (s.charAt(i) == s.charAt(i + 1)) { table[i][i + 1] = 1; longestStr = s.substring(i, i + 2); maxLen = 2; } } // 3个字符或3个以上字符串判断,动态规划思想。 for (int L = 3; L <= length; L++)// L代表子字符串长度 { for (int i = 0; i <= length - L; i++) { int j = i + L - 1; if (s.charAt(i) == s.charAt(j)) { table[i][j] = table[i + 1][j - 1]; if (table[i][j] == 1 && L > maxLen) { longestStr = s.substring(i, j + 1); maxLen = L; } else table[i][j] = 0; } } } return longestStr; } //中心扩展法,要考虑奇对称和偶对称 public String longestPalindrome2(String s) { if (s.isEmpty()) { return null; } if (s.length() == 1) { return s; } String longest = s.substring(0, 1); for (int i = 0; i < s.length(); i++) { //奇扩展 String tmp = centerExpend(s, i, i); if (tmp.length() > longest.length()) { longest = tmp; } //偶扩展 tmp = centerExpend(s, i, i + 1); if (tmp.length() > longest.length()) { longest = tmp; } } return longest; } public String centerExpend(String s, int begin, int end) { while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) { begin--; end++; } String subS = s.substring(begin + 1, end); return subS; } public static void main(String[] args) { String s = "abb"; LongestPalindrome lp = new LongestPalindrome(); System.out.println(lp.longestPalindrome2(s)); } }