题目描述:
给你一个字符串 s
,找到 s
中最长的回文子串。
原理分析:
回文子串的情况主要有两种,一种是以单个字符对称,例如:121,以2为对称;另一种是以一对为中心,例如:1221,以22为中心。判断的标准在于看中心两侧是否一致。问题的关键在于找到对称中心,以及判断是否符合对称两侧一致。除此之外,需要注意的就是在遍历的时候不要超出范围,并且考虑到字符串为空和字符串中不存在回文的处理。
编程语言:C++
代码实现:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string longestPalindrome(string s);
int main()
{
string s;
string result;
cout << "请输入字符串:" << endl;
while (cin >> s)
{
//cin >> s;
result = longestPalindrome(s);
}
return 0;
}
string longestPalindrome(string s)
{
string s1;
int temp = 0;
int length = 0;
int pleft = 0;
int pright = 0;
if (s.size() == 1)
{
length = 1;
cout << "最长回文是:" << s << endl;
cout << "长度是:" << length << endl;
return s;
}
for (int i = 0; i < s.size() ; i++)
{
if (s[i] == s[i + 1]&&i+1<s.size())
{
pleft = i;
pright = i + 1;
while (pleft-1>=0&&pright+1<s.size()&& s[pleft - 1] == s[pright + 1])
{
--pleft;
++pright;
}
temp = pright - pleft + 1;
if (temp > length)
{
length = temp;
s1 = s.substr(pleft, length);
}
//i = pright;
//continue;
}
if (i-1>=0&&s[i - 1] == s[i + 1])
{
pleft = i-1;
pright = i + 1;
while (pleft - 1 >= 0 && pright + 1 < s.size()&& s[pleft - 1] == s[pright + 1])
{
/*
if (s[pleft - 1] == s[pright + 1])
{
--pleft;
++pright;
}
*/
--pleft;
++pright;
}
temp = pright - pleft + 1;
if (temp > length)
{
length = temp;
s1 = s.substr(pleft, length);
}
//i = pright;
//continue;
}
}
if (length == 0)
{
s1 = s.substr(0, 1);
length = 1;
}
cout << "最长回文是:" << s1 << endl;
cout << "长度是:" << length << endl;
return s1;
}