- 题目描述:给你一个字符串,输出连续出现3次及以上的字符的首尾下标(注:是连续出现的位置)
思路
- 定义首尾指针,初始化都指向0下标
- 尾指针遍历整个字符串,当首尾字符相同时,则尾指针向前走,当走到首尾字符不同时,计算首尾相隔距离
- 当距离>=3,则把这组首尾下标添加到结果集中
- 更新首指针到尾指针的位置
- 重复以上步骤,直到尾指针遍历完整个字符串
class Solution { public List<List<Integer>> largeGroupPositions(String S) { List<List<Integer>> position=new ArrayList<>(); int end=0; int start=0; while(end<S.length()){//遍历整个字符串 while(end<S.length()&&S.charAt(start)==S.charAt(end)){//若有连续相同字符 end++;//尾指针往后走 } if(end-start>=3){//只要首尾相隔>=3,则记录下首尾位置,加到结果集中 position.add(Arrays.asList(start,end-1)); } start=end;//头指针可直接略过之前比较过的与之字符相同的位置,而是更新到当前的尾指针位置 } return position; } }
- 法2
class Solution {
public List<List<Integer>> largeGroupPositions(String S) {
List<List<Integer>> result = new ArrayList<>();
if (S == null || S.isEmpty()) return result;
int startIndex = 0;
int count = 1;
char c = S.charAt(startIndex);
for (int i = 1; i < S.length(); i++) {
if (S.charAt(i) != c) {
addToResult(startIndex, count, result);
c = S.charAt(i);
startIndex = i;
count = 1;
} else {
count++;
}
}
addToResult(startIndex, count, result);
return result;
}
private void addToResult(int startIndex, int count, List<List<Integer>> result) {
if (count >= 3) {
List<Integer> list = new ArrayList<>();
list.add(startIndex);
list.add(startIndex + count-1);
result.add(list);
}
}
}