830. Positions of Large Groups

原题

  • 题目描述:给你一个字符串,输出连续出现3次及以上的字符的首尾下标(注:是连续出现的位置)
  • 思路

    1. 定义首尾指针,初始化都指向0下标
    2. 尾指针遍历整个字符串,当首尾字符相同时,则尾指针向前走,当走到首尾字符不同时,计算首尾相隔距离
    3. 当距离>=3,则把这组首尾下标添加到结果集中
    4. 更新首指针到尾指针的位置
    5. 重复以上步骤,直到尾指针遍历完整个字符串
    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);
        }
    }
}
发布了80 篇原创文章 · 获赞 35 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章