830. Positions of Large Groupsjava
題目大意:shell
字符串按連續相同字符分組,超過3個就返回首字符和尾字符code
思路 :ip
舉例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實現:leetcode
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; }