题目描述: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.

求解的是字符串中最长的回文子串,跟求解最长子串不一样,不可以再使用哈希表来标记字符上次出现的位置,要想求解这个问题我们就要寻找和最长子串不一样的地方,回文无非就是对称的字符串。比如对应字符串中的位置i,我们可以求解出来以i为中心的回文子串长度(要在长度为奇数的时候,当回文子串为偶数的时候就是以i和i+1为中心的子串),可以通过两个辅助指针向两侧的移动来判断回文子串是否成立。我们把上面的过程当做一个函数来使用,返回以i为中心的子串长度,再在主函数中跟暂存的最大长度比较,这样不失为一种求解的方法。参考代码如下:


class Solution {
public:

int sublength(const string & s,int i,int j)
{
	int curLen = 0;//以i为中心的回文子串的长度
	while(i>=0&&j<s.length()&&s[i]==s[j])
	{
		i--;
		j++;
	}
	curLen = (j-1)-(i+1)+1;
	return curLen;
}

    string longestPalindrome(string s) {
        int startpos = 0;//回文子串起始的位置,最短的回文子串长度为1
	int max = 1;//暂存的回文子串的最大长度
	for(int i = 0;i<s.length();i++)
	{          //可能是以i为中心也可能是以i+1 为中心,取长者为当前的中心长度
		int curLen = (sublength(s,i,i)>sublength(s,i,i+1))?sublength(s,i,i):sublength(s,i,i+1);
		if(curLen>max)
		{
			max = curLen;
			if (max & 0x1)  //最大长度是奇数还是偶数
                  startpos = i - max / 2;  
                else   
                  startpos = i - (max - 1) / 2;  

		}
	}
	return s.substr(startpos,max);//返回找到的子串,起始位置和最大长度
    }
};