字符统计

173 篇文章 3 订阅
90 篇文章 0 订阅


Problem Link:点击打开链接


题目描述

    统计一个给定字符串中指定的字符出现的次数。 
输入描述:
    测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到'#'时输入结束,相应的结果不要输出。


输出描述:
    对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
    c0 n0
    c1 n1
    c2 n2
    ... 
    其中ci是第1行中第i个字符,ni是ci出现的次数。

输入例子:
I
THIS IS A TEST
i ng
this is a long test string
#

输出例子:
I 2
i 3
  5
n 2
g 2


解法1:

AC code:

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<map>
#include<math.h>
#include<string.h>
#include<queue>
#include<vector>
#include<set>
#define LL long long
#define exp 1e-9
#define MAXN 1000010

using namespace std;

int main()
{
//	freopen("D:\\in.txt","r",stdin);
	int i,j,l1,l2,n;
    while(1)
    {
    	char s1[8],s2[88];
    	gets(s1);
    	if(s1[0]=='#') break;
    	gets(s2);
    	l1=strlen(s1);
    	l2=strlen(s2);
    	for(i=0;i<l1;++i)
    	{
    		n=0;
    		for(j=0;j<l2;++j)
    		{
    			if(s1[i]==s2[j])
    				++n;
			}
			printf("%c %d\n",s1[i],n);
		}
	}
	return 0;
}


解法2(算法优化):

由于在英文状态下,计算机最多能够输入128种不同的字符,因此无需两个字符串每个字符一一比较,而是扫一遍即可。

AC code:

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<map>
#include<math.h>
#include<string.h>
#include<queue>
#include<vector>
#include<set>
#define LL long long
#define exp 1e-9
#define MAXN 1000010

using namespace std;

int main()
{
//	freopen("D:\\in.txt","r",stdin);
	int i,j,l1,l2,n;
    while(1)
    {
    	char s1[8],s2[88];
    	gets(s1);
    	if(s1[0]=='#') break;
    	int cnt[128]={0};
    	gets(s2);
    	l1=strlen(s1);
    	l2=strlen(s2);
		for(j=0;j<l2;++j)
		{
			cnt[s2[j]]++;
		}
    	for(i=0;i<l1;++i)
    	{
			printf("%c %d\n",s1[i],cnt[s1[i]]);
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林下的码路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值