杭电acm1000c语言答案,杭电oj1860:统计字符(字符串hash / 水题)(示例代码)

统计字符

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Problem Description

统计一个给定字符串中指定的字符出现的次数

Input

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

Output

对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:

c0 n0

c1 n1

c2 n2

...

其中ci是第1行中第i个字符,ni是ci出现的次数。

Sample Input

I

THIS IS A TEST

i ng

this is a long test string

Sample Output

I 2

i 3

5

n 2

g 2

注:第2个测试用例中,空格也是被统计的字符之一。

采用了一种比较麻烦的方法:字符串的hash方法

#include

using namespace std;

inline int hashFunc(char c)

{

int hashValue;

if(c >= 'A' && c <= 'Z')

hashValue = 257 + c - 'A';

else if(c >= 'a' && c <= 'z')

hashValue = 257 + 26 + c - 'a';

else

hashValue = 0 + c - ' ';

return hashValue;

}

int main()

{

//freopen("in.txt","r", stdin);

string str1, str2;

while(getline(cin, str1), str1!="#")

{

getline(cin, str2);

int arr[400] = {0};

for(int i=0;i

arr[hashFunc(str2[i])]++;

for(int i=0;i

printf("%c %d

",str1[i], arr[hashFunc(str1[i])]);

}

return 0;

}

下边的是一种简单的方法:

#include

#include

#include

using namespace std;

int main() {

char a[6], b[81];

int ans[256]={0};

while (gets(a) && a[0] != '#') {

gets(b);

memset(ans,0,256*sizeof(int));

// 统计出每个字符的出现次数

for(int i=0;i

ans[b[i]]++;

}

// 直接输出结果

for(int i=0;i

printf("%c %d

", a[i], ans[a[i]]);

}

}

return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值