LeetCode 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

在一个由小写字母构成的字符串 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

题解,要求一个数组中,某个元素连续出现3次以上的即为较大分组,要求输出在该数组中所有较大分组的起始元素位置和终止元素位置,并将这些位置保存在list中。我这里采用两层循环,外层采用for循环,一个一个遍历数组元素,内层再用一个while循环来遍历,每次以3个相同的元素为界,如果出现连续的3个相同元素,那么就要引起注意了!

public List<List<Integer>> largeGroupPositions(String S)
    {
        List<List<Integer>> list = new ArrayList<>();
        for(int i = 0; i < S.length(); i++)
        {
            if((i + 1) < S.length() && (i + 2) < S.length() && (S.charAt(i) ==
                    S.charAt(i + 1)) && (S.charAt(i + 1) == S.charAt(i + 2)))
            {
                int start = i;
                //System.out.println(start);
                int end = start + 2;
                while((end + 1 < S.length()) && S.charAt(end) == S.charAt(end + 1)){
                    end++;
                }
                List<Integer> res = new ArrayList<>();
                res.add((int)start);
                res.add((int)(end));
                list.add(res);
                i = end;
            }
        }
        return list;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值