830. Positions of Large Groups。

版权声明:本文为博主原创文章,转载请标明出处:http://blog.csdn.net/leafage_m https://blog.csdn.net/Leafage_M/article/details/85855645

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

原文链接:https://leetcode.com/problems/positions-of-large-groups/


题目给一个字符串,字符串中有些字母是连续出现的,我们需要统计出连续出现3次以上的字母位置,分别把该字母的开始位置和结束位置记录下来并返回,由于可能有多个字母都满足情况,所以返回的是一个二维数组,每个子数组中都记录了一个字母的开始位置和结束位置。


我们只需要遍历这个字符串,然后依次比较相邻字母是否相同,如果相同的话就把计数器count进行加一,当发现相邻两个字母不相同的话,就查看count是否大于3,如果大于3就代表上一个字母连续出现了3次以上,这时候就需要把上个字母的开始位置和结束位置记录下来,并且将count清零从新开始统计。可以利用遍历时的 i 和count做差加一来得出开始位置和结束位置。

在这里插入图片描述

class Solution {
public:
    vector<vector<int>> largeGroupPositions(string S) {
        vector<vector<int>> result;
        int count=1;
        for(int i=0,j=1;i<S.length();i++,j++) {
            if(S[i] == S[j]) {// 如果连续两个字母相等,则统计数目加一
                count++;
            } else {
                if(count >= 3) { // 如果连续次数大于3,则加入结果中
                    //cout << "i:" << i << ",count:" << count;
                    vector<int> temp = {i-count+1,i};
                    result.push_back(temp);
                }
                count=1;
            }
        }
        return result;
    }
};

另一种思路是,将一个字母第一次出现的位置标记为开始位置,然后向后遍历,当后面的与开始位置上的字母一样时就继续向后,直到出现新的字母,此时新的字母位置就是上一个字母的结束位置,用结束位置和开始位置就能计算出这个字母出现了多少次,如果大于3次则加入最后的结果中,并且重新设置开始位置。

在这里插入图片描述

class Solution {
public:
    vector<vector<int>> largeGroupPositions(string S) {
        int start=0, end=0, n=S.size();
        vector<vector<int>> res;
        while(end<n)
        {
            while(end<n && S[end]==S[start])// 如果当前的字符等于最开始的字符,则一直向后寻找
                end++;
            if(end-start>=3) { // 如果之间长度大于3,则加入结果
                res.push_back({start,end-1});
                //cout << "start:" << start << ",end:" << end << endl;
            }
            start=end;// 调整开始的位置
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/Leafage_M/article/details/85855645
今日推荐