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

Example 1:

Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.

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]]

题目:输入一个字符串(只包含小写字母),如果连续出现三个及以上的相同字符,则这一串相同字符的起点和终点index构成一个大组,返回输入字符串中所有大组构成的集合。

实现思路:双指针。令指针i和j的初始值是0。指针移动的规则是,①如果i和j所指字符相同,则移动j直到i和j指向不同字符;②此时可得连续出现的相同字符数量是j - i,根据题目要求,如果j - i >= 3则将i和j构成一个集合并加入最终结果,然后令i = j并再次执行①。

class Solution {
    public List> largeGroupPositions(String S) {
        if (S == null) throw new IllegalArgumentException("argument is null");
        List> result = new ArrayList<>();
        int length = S.length();
        int i = 0, j = 0;
        while (i < length) {
            while (j < length && S.charAt(i) == S.charAt(j))
                j++;
            if (j - i >= 3)
                result.add(Arrays.asList(i, j - 1));
            i = j;
        }
        return result;
    }
}

 

你可能感兴趣的:(LeetCode,LeetCode)