思路:
这个题目的解题思路是,要将不同的条件下的编程统一起来。比如,最长的回文子串需要以一个字符或两个相同的字符为中心向两边扩展。其实,一个字符可以等效于同一位置的两个字符。终止条件的统一处理,终止有两个原因:字符串到了边界,两边字符不相等,要注意将两种不同情况下终止的后续处理统一起来。
题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
class Solution {
public:
string getsub(string str,int i,int j)
{
int low=i;
int hi=j;
while(low>=0 && hi<(str.size()))
{
if(str[low]==str[hi])
{
low--;
hi++;
}
else
{
break;
}
}
return str.substr(low+1,hi-low-1);
}
string longestPalindrome(string s) {
if(s.size()<=1) return s;
string longest;
string temp;
for(int i=0;i<s.size()-1;i++)
{
temp=getsub(s,i,i);
if(temp.size()>longest.size()) longest=temp;
if(s[i]==s[i+1]) temp=getsub(s,i,i+1);
if(temp.size()>longest.size()) longest=temp;
}
return longest;
}
};