1. 程式人生 > >leetcode (Positions of Large Groups)

leetcode (Positions of Large Groups)

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;

    }