题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
思路:
采用简单暴力的遍历搜索方式,分析题目的回文形式,可分为两种:单数回文和双数回文。在遍历的过程中,不断进行回文检测,更新最大的回文子串的长度,记录相应的索引。
代码:
/*
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
*/
#include <string>
using namespace std;
class Solution {
// 回文检测算法函数
void longestPalindrome(const string& s, int a, int b, int& start, int& last)
{
// 字符串总长度
int len = s.size();
// 在起始索引处向两侧扩张地检测索引
while (a >= 0 && b < len && s[a] == s[b])
{
a--;
b++;
}
// 将回文的索引设置为正确的位置
a++;
b--;
// 如果当前的回文长度大于历史回文长度,则更换回文子串前后索引
if (b - a > last - start)
{
start = a;
last = b;
}
}
public:
string longestPalindrome(string s) {
// 字符串总长度
int len = s.size();
// 判断若为空串,直接返回此空串
if (len == 0)
return s;
// 创建回文的起始和终止索引
int start = 0, last = 0;
// 一次遍历
for (int i = 0; i < len - 1; i++)
{
// 单数的回文长度检测
longestPalindrome(s, i, i, start, last);
// 双数的回文长度检测
longestPalindrome(s, i, i + 1, start, last);
}
//返回回文字符串
return s.substr(start, last - start + 1);
}
};