[One question per day] Likou 830. Larger group position

Title description ( portal )

In a string s composed of lowercase letters, it contains a group of consecutive identical characters.

For example, in the string s = "abbxxxxzyy", there are some groups such as "a", "bb", "xxxx", "z" and "yy".

The grouping can be represented by the interval [start, end], where start and end represent the subscripts of the start and end positions of the group respectively. The “xxxx” grouping in the above example is represented by the interval [3,6].

We call all groups that contain more than or equal to three consecutive characters as larger groups.

Find each larger grouping interval, sort by the starting position index in ascending order, and return the result.

Example 1:

输入:s = "abbxxxxzzy"
输出:[[3,6]]
解释:"xxxx" 是一个起始于 3 且终止于 6 的较大分组。

Example 2:

输入:s = "abc"
输出:[]
解释:"a","b""c" 均不是符合要求的较大分组。

Example 3:

输入:s = "abcdddeeeeaabbbcd"
输出:[[3,5],[6,9],[12,14]]
解释:较大分组为 "ddd", "eeee""bbb"

Example 4:

输入:s = "aba"
输出:[]

Problem solving ideas & code implementation

public List<List<Integer>> largeGroupPositions(String s) {
    
    
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        int count = 1;int i = 0;
        for (; i < s.length() - 1; i++) {
    
    

            if (s.charAt(i) == s.charAt(i + 1)) {
    
    
                count++;// 统计
            }  else if (count >= 3) {
    
    
                list.add(Arrays.asList(i - count + 1, i));// 如果大于就添加到list,注意count从1开始
                count = 1;

            }else {
    
    
                count = 1;//这里有可能前边bbaaaa这种情况,bb只有2个,则要将count置为1,
            }
            
        }
        if(count>=3 && i == s.length()-1 && s.charAt(i) == s.charAt(i-1)){
    
    
                list.add(Arrays.asList(i-count+1,i));
             }// 考虑bbbb结尾的时候特殊判断,单独添加进去
        return list;

    }

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/112222888