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

这道题的主要思路在于确定有两种形式的对称,一种是直接对象比如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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值