题解 | #找位置#

找位置

https://www.nowcoder.com/practice/e3b2cc44aa9b4851bdca89dd79c53150

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

typedef struct KeyValue {
    char key;//字符
    int position[100];//出现的位置
    int cnt;//出现的次数
} KeyValue ;

KeyValue* stas[26 + 26 + 10]; //统计结构体数组
int n = 0; //记录出现字符的种类

_Bool isNotExist(int position, char c) {
    //后续字符先判断是否已经存在,若存在则修改,若不存在则加入
    int i = 0;
    for ( i = 0; i < n; i++) {
        if (stas[i]->key == c) {
            stas[i]->position[stas[i]->cnt] = position;
            stas[i]->cnt += 1;
            return false;
        }
    }
    return true;
}

void insert(int positin, char c) {
    KeyValue* newKV;
    if (isNotExist(positin,
                   c)) { //如果是第一个字符或者不存在的字符,则直接加入
        newKV = malloc(sizeof(KeyValue));
        newKV->cnt = 0;
        newKV->key = c;
        newKV->position[newKV->cnt] = positin;
        newKV->cnt += 1;
        stas[n] = newKV;
        n++;
    }
}

int main() {
    int a, b;
    char str[100];
    while (gets(str)) { // 注意 while 处理多个 case
        // 64 位输出请用 printf("%lld") to
        int i = 0;
        n = 0;
        for (i = 0; i < strlen(str); i++) {
            insert(i, str[i]);
        }
        int j = 0;
        for (i = 0; i < n; i++) {
            if (stas[i]->cnt > 1) {
                for (j = 0; j < stas[i]->cnt; j++) {
                    printf("%c:%d", stas[i]->key, stas[i]->position[j]);
                    if(j!=stas[i]->cnt-1){
                        printf(",");
                    }
                }
                printf("\n");
            }

        }
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务