830. Positions of Large Groups - C语言

本文介绍了一种算法,用于在小写字符串中定位长度为3或以上的连续相同字符组的起始和结束位置。通过一次遍历字符串并计数每个字符出现次数的方法,实现了对大型字符组的有效识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

830. Positions of Large Groups


In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = "abbxxxxzyy" has the groups "a""bb""xxxx""z" and "yy".

Call a group large if it has 3 or more characters.  We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

考察点:一个指针遍历S,一个指针记录每个字符出现的次数。注意返回值

My method:

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** largeGroupPositions(char* S, int** columnSizes, int* returnSize) {
    int i = 0, j;
    int k = 0;
    int **ret = (int **)malloc(sizeof(int *) * 334);
    *columnSizes = (int *)malloc(sizeof(int) * 334);
    *returnSize = 0;
    
    while (S[i]) {
        j = i + 1;
        int ct = 1;
        char tmp = S[i];
        while (S[j] && (S[j] == tmp)) {
            ct++;
            j++;
        }
        if (ct >= 3) {
            (*columnSizes)[k] = 2;
            ret[k] = (int *)malloc(2 * sizeof(int));
            ret[k][0] = i;
            //printf("k=%d, ret[k][0]=%d\n", k, i);
            ret[k][1] = j - 1;
            //printf("k=%d, ret[k][1]=%d\n", k, j-1);
            k++;
            (*returnSize)++;
        }
        i = j;
    }
    return ret;
}

Submission Detail

202 / 202 test cases passed.

Status: 

Accepted

Runtime: 4 ms

Submitted: 0 minutes ago

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值