子串计算

(某个题解的好方法,不是自己写的,还写不出来= =)

题目描述
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入描述:

输入包含多行,每行一个字符串。

输出描述:

对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。

示例1
输入

10101

输出

0 2
01 2
1 3
10 2
101 2

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define N 5050
#define LEN 101
using namespace std;

struct STR{
    char s[LEN];//子串
    unsigned count;//计数
}buf[N];//子串集合
int n;//子串的数量
char str[LEN];//读取的字符串
char child[LEN];//临时存储子串

void MakeChild(int from, int len)
{//读取字符串中的子串,存入child字符串。子串从from开始,长度为len
    for(int i=0; i<len; i++)
    {
        child[i]=str[from+i];
    }
    child[len]='\0';
}

bool cmp(STR a, STR b)
{
    return strcmp(a.s, b.s)<0;
}

void LetsGo()//生成子串列表并完成统计
{
    int len=strlen(str);
    for(int i=1; i<len; i++)//i是子串长度
    {
        for(int from=0; from+i<=len; from++)
        {
            MakeChild(from, i);//生成子串
            bool repeat=false;//用来检查这个字串以前是否出现过。先假设没出现过
            for(int i=0; i<n; i++)
            {
                if(strcmp(buf[i].s, child)==0)
                {//如果这个字串以前就出现过,那就直接计数器+1
                    buf[i].count++;
                    repeat=true;
                    break;
                }
            }
            if(!repeat)
            {//这个字串之前没出现过,那就把这个字串加入字串列表,计数器为1
                buf[n].count=1;
                strcpy(buf[n++].s, child);
            }
        }
    }
}

int main()
{
    while(gets(str))
    {
        n=0;//子串列表清零
        LetsGo();//生成子串列表并完成统计
        sort(buf, buf+n, cmp);//给子串列表排序
        for(int i=0; i<n; i++)
        {
            if(buf[i].count>1)//如果出现过不止一次,那就输出
            {
                printf("%s %d\n", buf[i].s, buf[i].count);
            }
        }
    }
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值