leetcode-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.

 

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

 

要完成的函数:

vector<vector<int>> largeGroupPositions(string S) 

 

说明:

1、给定一个字符串S,如果一个字符连续出现三次及三次以上,那么它就是一个“大组合”,要求找出所有“大组合”的起始位置和结束位置,最终以vector<vector<int>>的形式返回。

2、明白题意,这又是一道简单题。

直接贴上代码(附详解),如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
vector<vector<int>> largeGroupPositions(string S)
{
    int s1=S.size(),i=0,j;
    vector<vector<int>>res;//最后返回的vector
    vector<int>res1;//子vector
    while(i<s1-2)
    {
        if(S[i]==S[i+1]&&S[i]==S[i+2])//如果满足条件
        {
            res1.clear();//清空res1
            res1.push_back(i);//插入起始位置到res1
            j=i+3;
            while(j<s1)//找到不等于S[i]的字符位置
            {
                if(S[i]==S[j])
                    j++;
                else
                    break;
            }
            res1.push_back(j-1);//插入结束位置到res1
            res.push_back(res1);//res1插入到res里面
            i=j;//更新i的值
        }
        else
            i++;
    }
    return res;
}

上述代码实测13ms,因为服务器接收到的cpp submissions有限,所以没有打败的百分比。

posted @   chenjx85  阅读(181)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示