Description
Given a string s, find the longest palindromic substring ins. You may assume that the maximum length ofs is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
class Solution {
public:
bool huiwen(string s)
{
int i = 0, j = s.length() - 1;
if (j == 0)return true;
while (i <= j)
{
if (s[i] != s[j])
return false;
else
{
i++; j--;
}
}
return true;
}
string longestPalindrome(string s) {
int sum = 0, max = 0;
int a;
if (s.length() == 1)return s;
for (int i = 0; i<s.length() - 1; i++)
{
sum = 0;
for (int j = i; j < s.length(); j++)
{
if (s[i] == s[j])
{
sum = j - i + 1;
if (sum > max)
{
if (huiwen(s.substr(i, sum)))
{
a = i;
max = sum;
}
}
}
}
}
return s.substr(a, max);
}
};
本文介绍了一种寻找字符串中最长回文子串的方法。通过双重循环遍历字符串,利用辅助函数判断子串是否为回文,并记录最长回文子串的位置及长度,最终返回最长回文子串。
1187

被折叠的 条评论
为什么被折叠?



