【机试】子串计算 (STL)

子串计算

来源:北京大学

题目描述

给出一个01字符串(长度不超过100),求其每一个子串出现的次数。

输入描述

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

输出描述

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

示例

输入

10101

输出

0 2
01 2
1 3
10 2
101 2

 AC代码

#include<iostream>
#include<cstring>
#include<map>
using namespace std;
int main(void)
{
	string s;
	while(cin>>s)
	{
		map<string,int> m;
		for(int i=0;i<s.size();i++){
			for(int j=1;j<=s.size()-i;j++){
				m[s.substr(i,j)]++;
			}
		}
		map<string,int>::iterator it;
		for(it = m.begin();it!=m.end();it++){
			if(it->second>1)
				cout<<it->first<<" "<<it->second<<endl;
		}
	}
	return 0;
}

注意点:1.map的妙用。2.substr()的两个参数,第一个是起始位置,第二个是子串长度,其中第一个字符是位置0。

还可以构造结构体来存储子串。每一次提取一个子串出来后,先生成子串,然后和已有子串比较,如果有计数加1,否则创建子串后计数加1。不采用STL因此很考验基本功呀!

//https://www.nowcoder.com/questionTerminal/b44f5be34a9143aa84c478d79401e22a
#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值