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".
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of everylarge group sorted in increasing order by start index.
We scan the string and track the group boundaries using start and end indices. If a group’s length (end - start + 1) is at least 3, we record its interval in res.
#include<vector>#include<string>usingnamespace std;
vector<vector<int>> largeGroupPositions(string s) {
vector<vector<int>> res;
int n = s.size(), start =0;
for (int i =1; i <= n; ++i) {
if (i == n || s[i] != s[start]) {
if (i - start >=3) res.push_back({start, i-1});
start = i;
}
}
return res;
}
import java.util.*;
classSolution {
public List<List<Integer>>largeGroupPositions(String s) {
List<List<Integer>> res =new ArrayList<>();
int n = s.length(), start = 0;
for (int i = 1; i <= n; ++i) {
if (i == n || s.charAt(i) != s.charAt(start)) {
if (i - start >= 3) res.add(Arrays.asList(start, i-1));
start = i;
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
funlargeGroupPositions(s: String): List<List<Int>> {
val res = mutableListOf<List<Int>>()
var start = 0for (i in1..s.length) {
if (i == s.length || s[i] != s[start]) {
if (i - start >=3) res.add(listOf(start, i-1))
start = i
}
}
return res
}
1
2
3
4
5
6
7
8
9
10
deflargeGroupPositions(s: str) -> list[list[int]]:
res = []
n = len(s)
start =0for i in range(1, n+1):
if i == n or s[i] != s[start]:
if i - start >=3:
res.append([start, i-1])
start = i
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fnlarge_group_positions(s: String) -> Vec<Vec<i32>> {
let s = s.as_bytes();
let n = s.len();
letmut res =vec![];
letmut start =0;
for i in1..=n {
if i == n || s[i] != s[start] {
if i - start >=3 {
res.push(vec![start asi32, (i-1) asi32]);
}
start = i;
}
}
res
}
1
2
3
4
5
6
7
8
9
10
11
exportfunctionlargeGroupPositions(s: string):number[][] {
constres: number[][] = [];
letstart=0;
for (leti=1; i<=s.length; ++i) {
if (i===s.length||s[i] !==s[start]) {
if (i-start>=3) res.push([start, i-1]);
start=i;
}
}
returnres;
}