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.
本题求最长的回文子串,最简单的就是暴力求解,用中心扩展法,但是回文串有两种形式,奇abc和偶abba,两种情况都要考虑到。
#include<stdio.h>
#include<string.h>
int findodd(char *s,int i)//aba
{
int j;
for(j=0;i-j>=0&&s[i+j];j++)
{
if(s[i-j]!=s[i+j])
break;
}
return j;
}
int findeven(char *s,int i)//abba
{
int j;
for(j=0;i-j>=1&&s[i+j];j++)//开始这里我用的时i+j<strlen(s),结果时间有150多ms,用s[i+j]减到24ms,所以要慎用字符串函数啊啊啊
{
if(s[i+j]!=s[i-j-1])
break;
}
return j;
}
char* longestPalindrome(char* s)
{
int i,j,max,maxl,maxr;
max=0;
maxl=0;//回文子串左边开始位置
maxr=0;//回文子串右边结束位置
for(i=0;s[i];i++)
{
j=findodd(s,i);
if((2*j-1)>max)
{
max=2*j-1;
maxl=i-j+1;
maxr=i+j-1;
}
j=findeven(s,i);
if(2*j>max)
{
max=2*j;
maxl=i-j;
maxr=i+j-1;
}
}
s[maxr+1]='\0';
return s+maxl;
}
int main()
{
char s[100];
scanf("%s",s);
printf("%s\n",longestPalindrome(s));
return 0;
}
C++代码
class Solution {
public:
string str_helper(string s, int left, int right)
{
int n = s.length();
while(left>=0 && right<=n-1 && s[left]==s[right]){
left--;
right++;
}
return s.substr(left+1, right-left-1);
}
string longestPalindrome(string s) {
if(s.length() <= 1)
return s;
string longest = s.substr(0,1);
for (int i=0; i<s.length(); i++){
string tmp = str_helper(s, i, i);
if (tmp.length() > longest.length()) {
longest = tmp;
}
tmp = str_helper(s, i, i+1);
if (tmp.length() > longest.length()) {
longest = tmp;
}
}
return longest;
}
};