1.题目描述
- 较大分组的位置
在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。
例如,在字符串 s = “abbxxxxzyy” 中,就含有 “a”, “bb”, “xxxx”, “z” 和 “yy” 这样的一些分组。
分组可以用区间 [start, end] 表示,其中 start 和 end 分别表示该分组的起始和终止位置的下标。上例中的 “xxxx” 分组用区间表示为 [3,6] 。
我们称所有包含大于或等于三个连续字符的分组为 较大分组 。
找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。
2.思想
用两个变量记录相同的字符的开始索引和结束索引,当end-start>=2的时候,说明连续超过三次,则在和下一个字符不相等的时候将开始和结束索引存入数组。
3.代码
class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> arr = new ArrayList<>();
int start = 0,end = 0;
for(int i=1;i<s.length();i++){
if(s.charAt(i-1) == s.charAt(i) && i !=s.length()-1){
end++;
}else{
if(i ==s.length()-1 && s.charAt(i-1) == s.charAt(i)){
end++; //当最后一个数的时候要自增,并且进入到下面的判断
}
if(end - start >=2){
List<Integer> temp = new ArrayList<>();
temp.add(start);
temp.add(end);
arr.add(temp);
}
start = i;
end = i;
}
}
return arr;
}
}
List<Integer> temp = new ArrayList<>();
temp.add(start);
temp.add(end);
arr.add(temp);
如果把这新建List的这一步骤用arr.add(Arrays.asList(start, end));代替,代码会简洁很多,但同时也耗时更久,如下图: