Talk is cheap, show me the code.
一、问题描述
Catcher是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
输入描述:
输入一个字符串
输出描述:
返回有效密码串的最大长度
输入例子:
ABBA
输出例子:
4
二、问题分析
这是最长字符串回文问题,有多种思路。思路一,采用典型的最佳字符串回文问题解法manacher,复杂度是O(n)。思路二,类似于manacher,不过不用去考虑每个字符的初始回文半径,直接都设置为1,这样复杂度是O(n*n)。思路三,从字符串长度考虑起,逐个减少字符串长度直至为1,因为1个字符是最短的回文,时间复杂度是O(n * n * n)。
解题方式1:
采用manacher算法。manacher的原理详见http://blog.csdn.net/xingyeyongheng/article/details/9310555
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
string s = "#";
for (int i = 0; i < str.size(); i++)
{
s = s + str[i] + "#";
}
vector<int> vect;
int maxcenter = 0, maxright = 0;
int temp = 0;
for (int i = 0; i < s.size(); i++)
{
if (i >= maxright)
{
temp = 0;
} else {
temp = (vect[2 * maxcenter - i] > (maxright - i))?(maxright - i):vect[2 * maxcenter - i];
}
while (i - temp >= 0 && i + temp < s.size() && s[i - temp] == s[i + temp])
{
temp++;
}
vect.push_back(temp);
if ( temp > (maxright - maxcenter))
{
maxcenter = i;
maxright = i + temp;
}
}
cout << (maxright - maxcenter - 1) << endl;
}
return 0;
}
时间复杂度为O(n)。
解题方式2:
采用类似manacher的方式,但是直接将每个字符为中心时的回文半径设置为1。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
string str = "#";
for (int i = 0; i < s.size(); i++)
{
str = str + s[i] + "#";
}
int maxRadius = 1, temp = 1;
for (int i = 0; i < str.size(); i++)
{
temp = 1;
while (i - temp >= 0 && i + temp < str.size() && str[i - temp] == str[i + temp])
{
temp++;
}
if (temp > maxRadius)
{
maxRadius = temp;
}
}
cout << maxRadius - 1 << endl;
}
return 0;
}
时间复杂度为O(n * n)。
解题方式3:
从字符串长度逐个减一,一直到找到最长回文长度。
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
bool isSymmetric(string s)
{
for (int i = 0; i < s.size() / 2; i++)
{
if (s[i] != s[s.size() - 1 - i])
{
return false;
}
}
return true;
}
int main()
{
string s;
while (cin >> s)
{
int len = s.size();
int maxlen = 0;
for (int i = len; i > 0; i--)
{
for (int j = 0; j <= len - i; j++)
{
if (isSymmetric(s.substr(j, i)))
{
maxlen = i;
break;
}
}
if (maxlen != 0)
break;
}
cout << maxlen << endl;
}
return 0;
}
时间复杂度为O(n * n * n)。