Positions of Large Groups LT830
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"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
Example 2:
Input: "abc" Output: [] Explanation: We have "a","b" and "c" but no large group.
Example 3:
Input: "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]]
Note: 1 <= S.length <= 1000
Idea 1. two pointer, extend to the right until new element appears or reach the end of the input array.
Time complexity: O(n)
Space complexity: O(1) if not considering output List
loop the left pointer, as left pointer is fixed, expand the right pointer
1 class Solution { 2 public List<List<Integer>> largeGroupPositions(String S) { 3 List<List<Integer>> result = new ArrayList<>(); 4 for(int i = 0, right = 0; i < S.length(); i = right) { 5 6 while(right < S.length() && S.charAt(right) == S.charAt(i)) { 7 ++right; 8 } 9 10 if(right - i >= 3) { 11 result.add(Arrays.asList(i, right-1)); 12 } 13 } 14 return result; 15 } 16 }
Idea 1.a loop right pointer instead
1 class Solution { 2 public List<List<Integer>> largeGroupPositions(String S) { 3 List<List<Integer>> result = new ArrayList<>(); 4 for(int i = 0, right = 0; right < S.length(); ++right) { 5 6 while(right+1 < S.length() && S.charAt(right) == S.charAt(right+1)) { 7 ++right; 8 } 9 10 if(right - i + 1 >= 3) { 11 result.add(Arrays.asList(i, right)); 12 } 13 i = right + 1; 14 } 15 return result; 16 } 17 }
浙公网安备 33010602011771号