Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路:遍历字符串,以某一字符为中心,向两边扩展,判断两边对应的字符是否相等。
如:(1)对于字符串"dabcbag",最长回文子字符串为"abcba", 长度为5,为奇数。当遍历到字符c时,以字符串c为中心,记两边的字符下标分别为left,right,向两边扩展,left--, right++。判断两边的字符是否相等,b和b相等,再次向左右两边扩展,a和a相等,直到两边对应位置上的字符不相等,此时记录下长度(right-left+1)。
(2)同时存在"dabccbag",其最大回文字符串长度为6,即为偶数,"abccba"。这个时候以"cc"为中心,向两边扩展,寻找最长的子字符串长度。
Java代码实现
public class Solution {
public String longestPalindrome(String s) {
if(s.length() <= 1)
return s;
int left = 0;int ri