Positions of Large Groups-LeetCode#830

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

在小写字母的字符串S中,这些字母形成相同字符的连续组。

例如,诸如S =“abbxxxxzyy”的字符串具有组“a”,“bb”,“xxxx”,“z”和“yy”。
如果一个组有3个或更多字符,则调用它。我们想要每个大集团的起点和终点。

最终答案应该是字典顺序。
public class PositionsOfLargeGroups {
    public List<List<Integer>> largeGroupPositions(String S) {
        List<List<Integer>> res = new ArrayList<>();
        char temp = S.toCharArray()[0];
        int count = 0;
        int start = 0;
        int end = 0;
        for (int i = 0; i < S.length(); i++) {
            List<Integer> list = new ArrayList<>();
            if (temp == S.toCharArray()[i]) {
                count++;
            } else {
                if (count >= 3) {
                    end = i - 1;
                    list.add(start);
                    list.add(end);
                    res.add(list);
                }
                start = i;
                temp = S.toCharArray()[i];
                count = 1;
            }
            if (i == S.length() - 1) {
                if (count >= 3){
                    end = i;
                    list.add(start);
                    list.add(end);
                    res.add(list);
                }
            }
        }
        return res;
    }
    public static void main(String[] args) {
        PositionsOfLargeGroups positionsOfLargeGroups = new PositionsOfLargeGroups();
        positionsOfLargeGroups.largeGroupPositions("aaaaaaaabbb");
    }
}

ac时间很长啊,逻辑思路要换换

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部