题目:给定一个字符串,输出其中长度最大的回文字符串。
题解(1):遍历字符串,检查以字符串的某个(某相邻两个)字符为中心,向字符串左右展开,是否满足回文字符串的要求
class solution
{
private:
string str;
public:
solution(string strs) :str(strs) {};
void count() {
int count = 0; //记录最大回文字符串的长度
int record = 0; //记录回文字符串的起始位置
for (int i = 0;i < str.length()-2;i++)
{
int counts = 0;
int left = 0, right = 0; //左指针,右指针,用于拓宽回文字符串的长度
if (str[i] == str[i + 2]) //若回文字符串有中心单字符
{
counts = 3;
left = i - 1;
right = i + 3;
while (left >= 0 && right < str.length())
{
if (str[left] == str[right])
{
counts += 2;
left -= 1;
right += 1;
}
else {
break;
}
}
}
else if (str[i] == str[i + 1]) //若回文字符串无中心单字符
{
counts = 2;
left = i - 1;
right = i + 2;
while (left >= 0 && right < str.length())
{
if (str[left] == str[right])
{
counts += 2;
left -= 1;
right += 1;
}
else {
break;
}
}
}
if (count < counts) //记录当前长度最大的回文字符串
{
record = left + 1;
count = counts;
}
}
string res;
res = str.substr(record, count);
cout << res;
}
};
题解(2):遍历字符串中每一个子串,判断字串是否为回文字符串,在执行判断的过程中运用了动态规划的思想
class solution
{
private:
string str;
int result = 0;
int length = 0;
public:
solution(string strs) :str(strs) {};
void count() {
vector<vector<bool>>res(str.length(), vector<bool>(str.length(), false));
for (int i = 0;i < str.length();i++)
{
for (int start = 0;start + i < str.length();start++)
{
int end = 0;
end = start + i;
//若end=start,则一定是回文字符串
if (i == 0)
{
res[start][end] = true;
}
//若子字符串只有两个字符,只需判断这两个字符是否相等
else if (i == 1)
{
res[start][end] = (str[start] == str[end] )? true:false;
}
//判断是否满足子字符串的首字符等于尾字符,以及去首尾后的字符串是否是回文字符串,若满足,则为回文字符串
else {
if (str[start] == str[end] && res[start + 1][end - 1] == true && end - start >= 2)
{
res[start][end] = true;
}
}
if (res[start][end] == true&&length < end - start + 1)
{
length = end - start + 1;
result = start;
}
}
}
string strs;
strs = str.substr(result, length);
cout << strs<<endl;
}
};