package com.heu.wsq.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 830. 较大分组的位置
* @author wsq
* @date 2021/1/5
* 在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。
* 例如,在字符串 s = "abbxxxxzyy" 中,就含有 "a", "bb", "xxxx", "z" 和 "yy" 这样的一些分组。
* 分组可以用区间 [start, end] 表示,其中 start 和 end 分别表示该分组的起始和终止位置的下标。上例中的 "xxxx" 分组用区间表示为 [3,6] 。
* 我们称所有包含大于或等于三个连续字符的分组为 较大分组 。
* 找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。
*
* 示例 1:
* 输入:s = "abbxxxxzzy"
* 输出:[[3,6]]
* 解释:"xxxx" 是一个起始于 3 且终止于 6 的较大分组。
* 示例 3:
*
* 输入:s = "abcdddeeeeaabbbcd"
* 输出:[[3,5],[6,9],[12,14]]
* 解释:较大分组为 "ddd", "eeee" 和 "bbb"
*
* 链接:https://leetcode-cn.com/problems/positions-of-large-groups
*/
public class LargeGroupPositions {
public List<List<Integer>> largeGroupPositions(String s){
List<List<Integer>> ans = new ArrayList<>();
int start = 0;
char ch = ' ';
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (ch == ' '){
ch = c;
start = i;
continue;
}
if (ch != c){
if (i - start >= 3){
ans.add(Arrays.asList(start, i-1));
}
start = i;
ch = c;
}
}
if (s.length() - start >= 3){
ans.add(Arrays.asList(start, s.length()-1));
}
return ans;
}
public static void main(String[] args) {
String s = "abcdddeeeeaabbbcd";
LargeGroupPositions lg = new LargeGroupPositions();
List<List<Integer>> ans = lg.largeGroupPositions(s);
for (List<Integer> an : ans) {
for (Integer integer : an) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
830. 较大分组的位置
最新推荐文章于 2023-10-18 10:49:15 发布