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.