字符串类型题目和括号匹配类型题总结(持续更新)

1、匹配方案(卡特兰数)

问:长度为n的括号字符串,有多少种匹配方案?

令h(0)=1,h(1)=1,catalan数满足递推式:
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + … + h(n-1)*h(0) (n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式:
h(n)=h(n-1)(4*n-2)/(n+1)
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,…)
递推关系的另类解为:
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,…)

code:

#include <iostream>
using namespace std;
int main() {
    long long num[16];
    num[0]=1;
    num[1]=1;
    for(int i = 2;i<=15;i++)
        num[i] = num[i-1]*(4*i-2)/(i+1);
    printf("%lld",num[15]);
}

 

 

2、字符串哈希转换(相比map节约了时间和空间)

http://poj.org/problem?id=1200

题意:给定字符串,n,nc 。 nc表示该字符串不同字母个数, n表示切分成长度n的子串,问可切成不同子串数

思路:字符转换成数字的思想,例如 123 这个数字 是又1*100+2*10+3 组成,他拥有独一无二的地位,不会重复,那么如何给字符串分配类似的哈希值呢 , 假设现在有4种字符 ,a b c d  那么分别令为0123 ,那么abcd可以表示成 0*4*4*4 + 1*4*4 + 2*4 + 3

code:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>

using namespace std;
const int maxn = 16000005;

char st[maxn];
int hash[150];
bool mp[maxn];

int main()
{
    int n,m;
    memset(hash,0,sizeof(hash));
    memset(mp,0,sizeof(mp));

    while(~scanf("%d%d",&n,&m))
    {
        scanf("%s",st);
        int len = strlen(st);
        int cnt = 1;
        for(int i=0; i<len; i++)
            if(!hash[st[i]])
            {
                hash[st[i]] = cnt++;
            }
        int ans = 0;
        for(int i=0; i<=len-n; i++)
        {
            int tmp = 0;
            for(int j=i; j<n+i; j++)
            {
                tmp = tmp*m + hash[st[j]];
            }
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                ans++;
            }
            else
                mp[tmp] = 1;
                
        }
        printf("%d\n",ans);
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值