在一个由小写字母构成的字符串 S
中,包含由一些连续的相同字符所构成的分组。
例如,在字符串 S = "abbxxxxzyy"
中,就含有 "a"
, "bb"
, "xxxx"
, "z"
和 "yy"
这样的一些分组。
我们称所有包含大于或等于三个连续字符的分组为较大分组。找到每一个较大分组的起始和终止位置。
最终结果按照字典顺序输出。
示例 1:
输入: "abbxxxxzzy"
输出: [[3,6]]
解释: "xxxx" 是一个起始于 3 且终止于 6 的较大分组
。
示例 2:
输入: "abc" 输出: [] 解释: "a","b" 和 "c" 均不是符合要求的较大分组。
示例 3:
输入: "abcdddeeeeaabbbcd" 输出: [[3,5],[6,9],[12,14]]
说明: 1 <= S.length <= 1000
C
/**
* 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 n=strlen(S);
int k=0;
int m=n/3;
int** res=(int**)malloc(sizeof(int*)*m);
for(int i=0;i<m;i++)
{
res[i]=(int*)malloc(sizeof(int)*2);
}
*columnSizes=(int*)malloc(sizeof(int)*m);
int first=0;
int second=0;
int tmp=1;
for(int i=1;i<n;i++)
{
if(S[i]==S[i-1])
{
tmp++;
}
else
{
if(tmp>=3)
{
second=i-1;
res[k][0]=first;
res[k][1]=second;
(*columnSizes)[k]=2;
k++;
}
first=i;
tmp=1;
}
}
if(tmp>=3)
{
res[k][0]=first;
res[k][1]=n-1;
(*columnSizes)[k]=2;
k++;
}
*returnSize=k;
return res;
}
C++
class Solution {
public:
vector<vector<int>> largeGroupPositions(string S)
{
int n=S.length();
vector<vector<int>> res;
int first=0;
int second=0;
int tmp=1;
for(int i=1;i<n;i++)
{
if(S[i]==S[i-1])
{
tmp++;
}
else
{
if(tmp>=3)
{
second=i-1;
res.push_back(vector<int>{first,second});
}
first=i;
tmp=1;
}
}
if(tmp>=3)
{
res.push_back(vector<int>{first,n-1});
}
return res;
}
};
python
class Solution:
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
n=len(S)
tmp=1
res=[]
first=0
for i in range(1,n):
if S[i]==S[i-1]:
tmp+=1
else:
if tmp>=3:
second=i-1
res.append([first,second])
first=i
tmp=1
if tmp>=3:
res.append([first,n-1])
return res