1. 程式人生 > >830. Positions of Large Groups - LeetCode

830. Positions of Large Groups - LeetCode

.com esc posit question dde leetcode ddn class char

Question

830. Positions of Large Groups

技術分享圖片

Solution

題目大意:

字符串按連續相同字符分組,超過3個就返回首字符和尾字符

思路 :

舉例abcdddeeeeaabbbcd
  end  start  end-start
a 0    0      
b 1    0,1    1-0=1
c 2    1,2    2-1=1
d 3    2,3    3-2=1
d 4    3
d 5    3
e 6    3,6    6-3=3  3,5
e 7    6
e 8    6
e 9    6
a 10   6,10   10-6=4  6,9
a 11   10
b 12   10,12  12-10=2
b 13   12
b 14   12
c 15   12,15  15-12=3  12,14
d 16   13,14  16-15=1

Java實現:

public List<List<Integer>> largeGroupPositions(String S) {
    List<List<Integer>> retList = new ArrayList<>();
    if (S.length() < 3) return retList;
    int startIdx = 0, endIdx = 0;
    for (int i = 1; i < S.length(); i++) {
        endIdx = i;
        if (S.charAt(i) != S.charAt(startIdx)) {
            if (endIdx - startIdx > 2) {
                retList.add(Arrays.asList(startIdx, endIdx - 1));
            }
            startIdx = i;
        }
    }
    if (endIdx - startIdx > 1) {
        retList.add(Arrays.asList(startIdx, endIdx));
    }
    return retList;
}

830. Positions of Large Groups - LeetCode