Positions of Large Groups
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 every large group sorted in increasing order by start index.
Example 1:
Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Example 2:
Input: s = "abc"
Output: []
Explanation: We have groups "a", "b", and "c", none of which are large groups.
Example 3:
Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".
Constraints:
1 <= s.length <= 1000
s contains lowercase English letters only.
思路一:直接遍历,在遍历的过程中统计前后下标的距离是否大于等于 2
public List<List<Integer>> largeGroupPositions(String s) {
char[] chars = s.toCharArray();
int begin = 0;
int end = 0;
List<List<Integer>> result = new ArrayList<>();
for (int i = 1; i < chars.length; i++) {
if (chars[i] == chars[i - 1]) {
end = i;
} else {
List<Integer> t = new ArrayList<>();
t.add(begin);
t.add(end);
if (end - begin >= 2) {
result.add(t);
}
begin = i;
end = i;
}
}
if (end - begin >= 2) {
List<Integer> t = new ArrayList<>();
t.add(begin);
t.add(end);
result.add(t);
}
return result;
}
思路二:看了一下题解,发现在字符串后面追加一个字符,可以省去最后一个串的判断
标签:begin,end,groups,830,large,add,easy,group,leetcode From: https://www.cnblogs.com/iyiluo/p/17320132.html