- 題目描述:給你一個字符串,輸出連續出現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);
}
}
}