/** * @desc 对于长度为n的一个字符串A(仅包含数字,大小写英文字母),请设计一个高效算法,计算其中最长回文子串的长度。 ** 回文串,有着左右对称的特征,从首尾一起访问,遇到的元素都是相同的。但是我们这里正是要找最长的回文串, * 并不事先知道长度,怎么办?判断回文的过程是从首尾到中间,那我们找最长回文串可以逆着来,从中间延伸到首尾,这就是中心扩展法。 *
* step 1:遍历字符串每个字符。 * step 2:以每次遍历到的字符为中心(分奇数长度和偶数长度两种情况),不断向两边扩展。 * step 3:如果两边都是相同的就是回文,不断扩大到最大长度即是以这个字符(或偶数两个)为中心的最长回文子串。 * step 4:我们比较完每个字符为中心的最长回文子串,取最大值即可。 */ public class GetLongestPalindrome { public static int getLongestPalindrome(String str) { int max = 0; int length = str.length(); int i = 0; while (i < length) { int begin = i; int end = i; //先判断是否有相邻的元素,移动右下标 while (end < length - 1 && str.charAt(end) == str.charAt(end + 1)) { end++; } //修改初始值i的位置 i = end + 1; //如果左边下标跟右边下标相等,则分别左移动和右移 while (begin > 0 && end < length - 1 && str.charAt(begin - 1) == str.charAt(end + 1)) { begin--; end++; } max = Math.max(max, end - begin + 1); } return max; } public static void main(String[] args) { System.out.println(getLongestPalindrome("abcdefggfedcba")); } }