Longest Palindromic Substring
#include <cstring>
#include <iostream>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s == "")
return "";
int max = -1;
string result;
int length = s.length();
int g1,g2;
for(int i = 0;i < length;i++)
{
g1 = get11(s,i);
g2 = get12(s,i);
if(g2 > g1)
{
if(g2*2 > max)
{
result = s.substr(i-g2+1,g2*2);
max = g2*2;
}
}
else
{
if(g1*2+1>max)
{
result = s.substr(i-g1,g1*2+1);
max = g1*2+1;
}
}
}
return result;
}
int get11(string s,int p)
{
int i = 1;
int count = s.length();
while((p-i)>=0&&(p+i)<count&&s[p-i]==s[p+i])
{
i++;
}
return --i;
}
int get12(string s,int p)
{
int i = 0;
int count = s.length();
while((p-i)>=0&&(p+i+1)<count&&s[p-i]==s[p+i+1])
{
i++;
}
return i;
}
};
int main()
{
Solution s;
string t,a;
while(cin>>a){
t = s.longestPalindrome(a);
cout<<t<<endl;}
system("Pause");
return 0;
}
浙公网安备 33010602011771号