5. 最长回文子串
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
C++解法:
class Solution {
public:
bool Palindrome(string s, int start, int end)
{
int length = end - start + 1; //检测的字符串长度
int cycleIndex = 0; //循环次数
int count = 0; //计数器
int begin = start; //临时开始变量
int ending = end; //临时结束变量
if (length % 2 == 0)
{
cycleIndex = length / 2;
}
else
{
cycleIndex = (length + 1) / 2;
}
for (int i = start; i < (start + cycleIndex); ++i)
{
if (s[begin] == s[ending])
{
count++;
begin++;
ending--;
}
}
if (count == cycleIndex)
{
return true;
}
else
{
return false;
}
}
string longestPalindrome(string s)
{
int palindromeLength = 0; //最大回文字符串长度
string palindrome; //回文字符串
for (int i = 0; i < s.size(); ++i)
{
for (int j = i; j < s.size(); ++j)
{
if (s[i] != s[j])
{
continue;
}
if (Palindrome(s, i, j))
{
int length = j - i + 1;//回文字符串长度
if (palindromeLength <= length)
{
palindromeLength = length;
palindrome.clear();
palindrome.append(s.begin() + i, s.begin() + j + 1);
}
}
}
}
return palindrome;
}
};