https://leetcode.com/problems/positions-of-large-groups/description/
https://leetcode.com/problems/positions-of-large-groups/discuss/128957/C++JavaPython-Straight-Forward
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]]
public List<List<Integer>> largeGroupPositions(String S) {
List<List<Integer>> ans = new ArrayList();
int i = 0, N = S.length(); // i is the start of each group
for (int j = 0; j < N; ++j) {
if (j == N-1 || S.charAt(j) != S.charAt(j+1)) {
// Here, [i, j] represents a group.
if (j-i+1 >= 3)
ans.add(Arrays.asList(new Integer[]{i, j}));
i = j + 1;
}
}
return ans;
}
https://leetcode.com/problems/positions-of-large-groups/discuss/128957/C++JavaPython-Straight-Forward
For every groups, find its start index
Group length is
i
and end index j - 1
Group length is
j - i
, if it's no less than 3, add (i, j) to result. public List<List<Integer>> largeGroupPositions(String S) {
int i = 0, j = 0, N = S.length();
List<List<Integer>> res = new ArrayList<>();
while (j < N) {
while (j < N && S.charAt(j) == S.charAt(i)) ++j;
if (j - i >= 3) res.add(Arrays.asList(i, j - 1));
i = j;
}
return res;
}