华为OD机试C卷(100分)-连续字母长度(C语言)

题目描述

给定一个字符串,只包含大写字母,求在包含同一字母的子串中,长度第 k 长的子串的长度,相同字母只取最长的那个子串。

输入描述

第一行有一个子串(1<长度<=100),只包含大写字母。

第二行为 k的值

输出描述

输出连续出现次数第k多的字母的次数。

用例

输入
AAAAHHHBBCDHHHH
3

输出 2
说明
同一字母连续出现的最多的是A和H,四次;

第二多的是H,3次,但是H已经存在4个连续的,故不考虑;

下个最长子串是BB,所以最终答案应该输出2。

输入
AABAAA
2

输出 1
说明
同一字母连续出现的最多的是A,三次;

第二多的还是A,两次,但A已经存在最大连续次数三次,故不考虑;

下个最长子串是B,所以输出1。

输入 ABC
4
输出 -1
说明 只含有3个包含同一字母的子串,小于k,输出-1
输入 ABC
2
输出 1
说明 三个子串长度均为1,所以此时k = 1,k=2,k=3这三种情况均输出1。特此说明,避免歧义。

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

// Define a structure to represent the key-value mapping
struct KeyValue {
    char key;
    int value;
};

// Function to get the result
int getResult(char *s, int k) {
    if (k <= 0) return -1;

    int len = strlen(s);
    char *new_s = (char *)malloc((len + 2) * sizeof(char));
    strcpy(new_s, s);
    strcat(new_s, "0");

    struct KeyValue count[256]; // Assuming ASCII characters
    int count_size = 0;

    char b = new_s[0];
    int count_len = 1;

    for (int i = 1; i < len + 1; i++) {
        char c = new_s[i];

        if (b == c) {
            count_len++;
        } else {
            int found = 0;
            for (int j = 0; j < count_size; j++) {
                if (count[j].key == b) {
                    found = 1;
                    if (count[j].value < count_len) {
                        count[j].value = count_len;
                    }
                    break;
                }
            }
            if (!found) {
                count[count_size].key = b;
                count[count_size].value = count_len;
                count_size++;
            }
            count_len = 1;
            b = c;
        }
    }

    int arr[count_size];
    for (int i = 0; i < count_size; i++) {
        arr[i] = count[i].value;
    }

    if (k > count_size) return -1;
    else {
        for (int i = 0; i < count_size - 1; i++) {
            for (int j = i + 1; j < count_size; j++) {
                if (arr[i] < arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr[k - 1];
    }
}

int main() {
    char s[100];
    int k;

    printf("Enter the string: ");
    scanf("%s", s);
    printf("Enter k: ");
    scanf("%d", &k);

    int result = getResult(s, k);
    printf("Result: %d\n", result);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我不会起名字呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值