830. Positions of Large Groups

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;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9537770.html