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”.
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, “xxxx” has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of every large group sorted in increasing order by start index.

一个字符串里,有些字符连续出现。若一个字符连续出现的长度(次数)大于等于3,我们认为这组连续是长的,这时我们记录下这组连续字符的起始和终止脚标,加入到list中,返回list而且要保证脚标从小大大排列。

思路:
从左向右遍历可以保证输出是有序的。我们设立双指针,一个慢,一个快,慢的一开始指向0,快的一开始指向1 。 快的指针一步一步向前走,每一步检查是否与慢的指针指向的同一个字符,若相同则快的指针继续走(慢的指针不动),若不同则标志着此连续区间的结束,并计算连续区间的长度,若长度大于等于3则加入list,慢指针重设在快指针的位置,快指针加一(含在for循环里的)。注意最后的区间要手动结算。

代码如下:

class Solution {
    public List<List<Integer>> largeGroupPositions(String s) {
        int slower=0;
        List<List<Integer>> ans=new ArrayList<>();
        for(int faster=1; faster<s.length(); faster++){
            //case1: when the faster char is different from the slower char, we need to end the curr session
            if(s.charAt(slower)!=s.charAt(faster)){
                //specially, if the length of the subpart is >=3, we add it to the list
                if(faster-slower>=3){
                    List<Integer> list=new ArrayList<>();
                    list.add(slower);
                    list.add(faster-1);
                    ans.add(list);
                }
                slower=faster;
            }
        }
        if(s.length()-1-slower+1>=3){
            List<Integer> list=new ArrayList<>();
            list.add(slower);
            list.add(s.length()-1);
            ans.add(list);
        }
        return ans;
    }
}

时间复杂度:O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值