挑选回文串(二进制枚举)

回文串

Time Limit : 3000/400ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 36   Accepted Submission(s) : 10

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

最近郁闷的汪欧涛遇到了一个难题,他的队友小成成给了他一道问题,对于一串随机的字符串(均由小写字母组成),去掉任意位置上任意数量的字符,可以得到的最长的回文串长度是多少,这可把汪欧涛给难住了,你作为他的好朋友,你能帮他解决这个问题吗?
ps:“回文串”是一个正读和反读都一样的字符串,例如“abcba”,“a”,“adeeda”是回文串,而“abcd”,‘adc’不是。

Input

输入多组字符串,每组字符串皆由小写字母组成,每组字符串的长度不超过10。

Output

对于每组字符串,输出一个整数在一行,代表其能组成的回文串的最大长度。

Sample Input

abca

abdefacaed

aaaaaaaaaa

Sample Output

3
7
10

Author

moonlike
 
思路:以后碰到这种需要从串中挑选一些字符的题目,因为可以任意挑取,所以用二进制来挑选是很好的选择,为什么呢?  这样一种情况都不会落下,而且很好取值,具体看代码:
#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<ctype.h>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9;
const int maxn=200+5;
const int maxm=12880+5;
const int maxx=1e4+10;
const ll maxe=1000+10;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
/*
这一题都知道是要遍历所有可能的情况,但是怎么把所有情况挑选出来是一个
关键,感叹自己菜的同时表示很无奈,,没有想到用二进制的办法来抽取每一种情况
二进制位为1的话,代表该位置的字符要选取,这样所有情况一种都不会落下,很快能挑出所有情况
*/
int solve(char s[])
{
    int len=strlen(s);
    for(int i=0;i<len/2;i++)
    {
        if(s[i]!=s[len-1-i]) return 0;
    }
    return len;
}
int main()
{
    //string a;
    char a[15],b[15];
    while(scanf("%s",a)!=EOF)
    {
        //getchar();
        int ans=0;
        int len=strlen(a);
        for(int i=1;i<(1<<len);i++)//1和0代表该位挑出来还是不挑出来
        {
            //cout<<"*"<<i<<endl;
            strcpy(b,"");
            int tmp=i,n=0,m=0;
            while(tmp!=0)
            {
                if(tmp&1)
                {
                   b[m++]=a[n];
                }
                n++;
                tmp>>=1;
            }
            b[m]='';//这里不手动加''就错了
            //cout<<"*"<<b<<endl;
            ans=max(ans,solve(b));
        }
        printf("%d
",ans);
        //cout<<ans<<endl;
    }
    return 0;
}
当初的梦想实现了吗,事到如今只好放弃吗~
原文地址:https://www.cnblogs.com/caijiaming/p/9865714.html