Problem: Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S.
class Solution {
public:
string longestPalindrome(string s) {
int mx=0, start=-1;
for(int i=0;i<s.size();i++)
{
int mid = expandCenter(s, i, i);
if(mx < mid)
{
mx=mid;
start = i-mx/2;
}
int left = expandCenter(s, i, i+1);
if(mx < left)
{
mx=left;
start = i-mx/2+1;
}
}
return s.substr(start, mx);
}
int expandCenter(string s, int left, int right)
{
while(left>=0 && right<s.size() && s[left]==s[right])
{
left--, right++;
}
return right-left-1;
}
};
No comments:
Post a Comment