您的位置:首页 > 其它

华为oj 字符串运用-密码截取

2016-02-29 11:13 441 查看
这道题的主要思路在于确定有两种形式的对称,一种是直接对象比如ABBA,另外一种是中间存在一个对称轴的兑现比如bab.所以对于这两种形式需要分别处理,对每个字符查看当前是否满足对称中间的要求,然后向两边查找最长的值,最后两种情况得到的值进行对比取最大值即可。
#include<iostream>
#include<string>
using namespace std;

void getMax1(string s,int &type1) //对称的中间有值
{
int len = s.length();
if(len==1)
type1 = 1;
else
{
for(int i=0;i<len;i++)
{
int j = i-1;
int k = i+1;
if(j>=0&&k<len&&s[j]==s[k])
{
int temp = 1;
int left = j-1;
int right = k+1;
while(left>=0&&right<len)
{
if(s[left]==s[right])
{
++temp;
--left;
++right;
}
else
break;
}
if(type1<2*temp+1)
type1 = 2*temp+1;
}
}
}
}

void getMax2(string s,int &type2) //直接对称
{
int len = s.length();
for(int i=0;i<len;i++)
{
int j = i+1;
if(j<len && s[i] == s[j])
{
int temp = 1;
int left = i-1;
int right = j+1;
while(left>=0&&right<len)
{
if(s[left] == s[right])
{
++temp;
--left;
++right;
}
else
break;
}
if(type2<2*temp)
type2 = 2*temp;
}
}
}

void getMaxLength(string &s)
{
int type1 = 0,type2 = 0;
getMax1(s,type1);
getMax2(s,type2);
if(type1>type2)
cout<<type1<<endl;
else
cout<<type2<<endl;
}

int main()
{
string s;
while(getline(cin,s))
{
getMaxLength(s);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: