leetcode Day26----array.easy

在小写字母组成的字符串S中,相同字符连续出现形成不同的组。当一个组包含3个或更多字符时,称之为大组。题目要求找到所有大组的起始和结束位置,并按字典序排列输出。例如,输入""abbxxxxzzy"",输出[[3,6]],因为""xxxx""是唯一的大组。对于输入""abc"",没有大组,输出为空。对于输入""abcdddeeeeaabbbcd"",输出[[3,5],[6,9],[12,14]]。" 83905614,1091391,BTA网络探针安全机制详解,"['网络应用', '网络协议', '配置管理']
摘要由CSDN通过智能技术生成

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.

Example 1:

Input: “abbxxxxzzy”
Output: [[3,6]]
Explanation: “xxxx” is the single large group with starting 3 and ending positions 6.
Example 2:

Input: “abc”
Output: []
Explanation: We have “a”,“b” and “c” but no large group.
Example 3:

Input: “abcdddeeeeaabbbcd”
Output: [[3,5],[6,9],[12,14]]

Note: 1 <= S.length <= 1000

C语言

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

#define MAX_LENGTH 1000

int** largeGroupPositions(char * S, int* returnSize, int** returnColumnSizes){
    int **results;
    int size = 0;
    
    results = (int**)malloc(sizeof(int*) * MAX_LENGTH / 3);    
    *returnColumnSizes = (int*)malloc(sizeof(int) * MAX_LENGTH / 3);
    
    int i = 0, j = 0;
    while (S[i]) {
        while (S[i] == S[j])
            ++j;
        if (j - i >= 3) {
            results[size] = malloc(2 * sizeof(int));
            results[size][0] = i;
            results[size][1] = j - 1;
           (*returnColumnSizes)[size] = 2;
            ++size;
        }
        i = j;
    }
    
    *returnSize = size;
    return results; 
}

Success
Details
Runtime: 8 ms, faster than 97.06% of C online submissions for Positions of Large Groups.
Memory Usage: 8.9 MB, less than 87.50% of C online submissions for Positions of Large Groups.

python3

class Solution:
    def largeGroupPositions(self, S: str) -> List[List[int]]:
        i   = 0
        res = []
        while i < len(S):
            j = i + 1
            while j < len(S) and S[j] == S[i]:
                j = j + 1
            if (j - i) > 2:
                res.append([i, j - 1])
            i = j
            
        return res

Success
Details
Runtime: 52 ms, faster than 62.83% of Python3 online submissions for Positions of Large Groups.
Memory Usage: 13.3 MB, less than 6.98% of Python3 online submissions for Positions of Large Groups.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值