Description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Note:
“aba” is also a valid answer when you input "babad".
Solution:
Analysis and Thinking:
题目要去寻找给定字符串的最大回文子串,且同一字符串的结果可能有多个,只需给出其中一个即可。本文采用了backtrack的方法,为了排除不必要的判断增加的时间复杂度,可以从字符串每个单一字符开始向两边拓展,遇到相同字符相连的可以合并判断。以当前遍历位置的字符为中心往两边判断,一旦失败,就不用往外判断。其中,本文将形如"xbbbby"以及“abcda”两类字符串分开解决。
Steps:
1.输入测试字符串,判断是否为空或长度是否为1,若是,直接返回输入
2.定义并初始化记录最大回文子串的开始位置、长度、字符串遍历计数器三个变量startPos、maxStrLength、counter
3.判断输入字符串回文子串是否形如"abcda",若是,以遍历位置为中心向两边拓展,其中向左拓展为i-counter,向右
拓展为i+counter,一旦左右字符相等,更新最大长度为counter*2+1,开始位置为i-counter+2,并以当前回文子串为中心,继续外拓。
4.若否,奢侈repeatCounter变量,用于计数同一字符重复次数,将counter置0,向右拓展,直到下一个字符不等于当前字符,并
使得遍历位置i以及计数器repeatCounter随着遍历加1,之后进行形如3的操作,只是向左拓展操作为i-repeatCounter-counter
5.返回根据startPos,maxStrLength确定的子字符串
Codes:
class HW4Solution
{
public:
string getLongestPalindromic (string s)
{
if(s==""||s.size()==1)
return s;
int startPos=0,maxStrLength=0; //记录子串开始位置与长度
for(int i=0;i<s.size()-1;i++)
{
int counter=1;
if(s[i]!=s[i+1]) //从一个点向两边拓展
{
while(i-counter>=0&&i+counter<s.size()&&s[i-counter]==s[i+counter])
++counter;
if((counter-1)*2+1>maxStrLength)
{
maxStrLength=(counter-1)*2+1;
startPos=i-counter+1;
}
}
else
{
int repeatCounter=0;
counter=0;
while(i+1<s.size()&&s[i]==s[i+1])
{
i++;
repeatCounter++;
}
while(i-repeatCounter>=0&&i+counter<s.size()&&s[i-repeatCounter]==s[i+counter])
counter++;
if((counter-1)*2+1+repeatCounter>maxStrLength)
{
maxStrLength=(counter-1)*2+1+repeatCounter;
startPos=i-counter+1-repeatCounter;
}
}
}
return s.substr(startPos,maxStrLength);//返回指定起始位置子串
}
};
Results: