Question:

In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".

Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

Example:

  1. Input: "abbxxxxzzy"
  2. Output: [[3,6]]
  3. Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
  1. Input: "abc"
  2. Output: []
  3. Explanation: We have "a","b" and "c" but no large group.
  4. Input: "abcdddeeeeaabbbcd"
  5. Output: [[3,5],[6,9],[12,14]]

Solution:

  1. /**
  2. * @param {string} S
  3. * @return {number[][]}
  4. */
  5. var largeGroupPositions = function(S) {
  6. let result = [];
  7. let arr = S.split('');
  8. let curIndex = 0;
  9. let curItem = arr[0];
  10. let j = 1 ;
  11. for (let i = 1; i< arr.length ; i ++ ){
  12. if(arr[i]!=curItem){
  13. if(j >= 3) {
  14. result.push([curIndex, i-1])
  15. }
  16. curItem = arr[i];
  17. curIndex = i;
  18. j = 1;
  19. }else{
  20. j ++ ;
  21. if(i===arr.length-1 && j >=3){
  22. result.push([curIndex, i])
  23. }
  24. }
  25. }
  26. return result;
  27. };