题目:
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.
思路:
遍历整个字符串,针对每个字符从中间向两边计算对称字符串。计算对称字符串的时候要考虑奇数与偶数两种情况。
代码:
class Solution {
public:
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string max;
for(int i = 0; i < s.size(); i++)
{
string str = palindrome(s, i);
if(str.size() > max.size())
{
max = str;
}
}
return max;
}
string palindrome(string s, int i)
{
string str;
int low1 = i;
int high1 = i;
while(low1>=0 && high1 < s.size() && s[low1-1] == s[high1+1])
{
low1--;
high1++;
};
int low2 = i-1;
int high2 = i;
while(low2>=0 && high2 < s.size() && s[low2] == s[high2])
{
low2--;
high2++;
};
low2++;
high2--;
if(high1 - low1 >= high2 - low2)
{
for(int k = low1; k <= high1; k++)
str.push_back(s[k]);
}
else
{
for(int k = low2; k <= high2; k++)
str.push_back(s[k]);
}
return str;
}
};