Leetcode Leetcode 830. Location of larger group

Topic:

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:

Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is a larger group starting at 3 and ending at 6.

Example_2:

Input: s = "abc"
Output: []
Explanation: "a", "b" and "c" are not large groups that meet the requirements.

Example_3:

Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The larger groups are "ddd", "eeee" and "bbb"

Example_4:

Input: s = "aba"
Output: []

Solution:

Traverse the list s.
Record the occurrence of repeated numbers in each repeated array as count (the repeated array can also only appear once).
For each repeated array, the
traversed value is not equal to the next digit
or the entire sequence all traversing the complete array traversal can be used as repeat end condition is completed
at this time can determine whether the number of occurrences of this array is greater than three
, if greater than three, will start and end positions as a result of adding a new list res in
need when (Note judged complete traversal The condition that all traversed will be judged first)
(used to avoid out of bounds during array traversal) and
finally return to res to complete

Code:

class Solution:
    def largeGroupPositions(self, s: str) -> List[List[int]]:
        res = []
        n = len(s)
        count = 1

        for i in range(n):
            if i == n - 1 or s[i] != s[i + 1] :
                if count >= 3:
                    res.append([i - count + 1, i])
                count = 1
            else:
                count += 1
        
        return res

Answer:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112421343