leetcode (Positions of Large Groups)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84781547

Title:Positions of Large Groups   830

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/positions-of-large-groups/

1.  采用双指针,注意最后一个子串

时间复杂度:O(n),一次一层while循环,需要遍历整个数组。

空间复杂度:O(n),申请额外的空间List。

    /**
     * 双指针
     * @param S
     * @return
     */
    public static List<List<Integer>> largeGroupPositions(String S) {

        List<List<Integer>> list = new ArrayList();
        int startIndex = 0;
        int endIndex = startIndex + 1;

        while (endIndex < S.length()) {
            if (S.charAt(startIndex) == S.charAt(endIndex)) {
                endIndex++;
            }
            else {
                if (endIndex - startIndex >= 3) {
                    List<Integer> tmpList = new ArrayList<>();
                    tmpList.add(startIndex);
                    tmpList.add(endIndex - 1);
                    list.add(tmpList);
                }
                startIndex = endIndex;
                endIndex = startIndex + 1;
            }
        }

        // 最后一次是否存在大于3的相同的字符
        if (endIndex - startIndex >= 3) {
            List<Integer> tmpList = new ArrayList<>();
            tmpList.add(startIndex);
            tmpList.add(endIndex - 1);
            list.add(tmpList);
        }

        return list;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84781547