KY228 找位置

描述:
对给定的一个字符串,找出有重复的字符,并给出其位置,如:abcaaAB12ab12 输出:a,1;a,4;a,5;a,10,b,2;b,11,1,8;1,12, 2,9;2,13。
输入描述:
输入包括一个由字母和数字组成的字符串,其长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据, 按照样例输出的格式将字符出现的位置标出。 1、下标从0开始。 2、相同的字母在一行表示出其出现过的位置。
示例1

输入:
abcaaAB12ab12

输出:
a:0,a:3,a:4,a:9
b:1,b:10
1:7,1:11
2:8,2:12

知识点: 查找 哈希
AC代码:

#include <stdio.h>
#include <string.h>

typedef struct charTable {
    int tag; // 标记是否打印过
    int num; // 出现的次数
}charTable;

int main() {
    char str[105];
    charTable ct[1000];
    while(scanf("%s", str) != EOF) {
        for(int i = 0; i < strlen(str); i++) {
            ct[str[i]].num ++;
            ct[str[i]].tag = 0;
        }      
        for(int i = 0; i < strlen(str); i++) {
            if(ct[str[i]].num > 1 && ct[str[i]].tag == 0) {
                int j = i;
                int cnt = 1;
                while(cnt <= ct[str[i]].num) {
                    if(str[j] == str[i] && cnt < ct[str[i]].num) {
                        printf("%c:%d,", str[i], j);
                        cnt ++;
                    }
                    else if(str[j] == str[i] && cnt == ct[str[i]].num) {
                            printf("%c:%d\n", str[i], j);
                            break;
                    }
                    
                    j ++;
                }
                ct[str[i]].tag = 1;
            }
        }
    }
    return 0;
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值