carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode830:较大分组的位置(positions-of-large-groups) #143

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。

例如,在字符串 s = "abbxxxxzyy" 中,就含有 "a", "bb", "xxxx", "z" 和 "yy" 这样的一些分组。

分组可以用区间 [start, end] 表示,其中 start 和 end 分别表示该分组的起始和终止位置的下标。上例中的 "xxxx" 分组用区间表示为 [3,6] 。

我们称所有包含大于或等于三个连续字符的分组为 较大分组 。

找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。

 

示例 1:

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

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

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

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

1 <= s.length <= 1000 s 仅含小写英文字母

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/positions-of-large-groups

carloscn commented 1 year ago

问题分析

fn position_of_large_groups(s: &String) -> Vec<Vec<i32>>
{
    let mut ret_vec:Vec<Vec<i32>> = vec![];
    let in_chars:Vec<u8> = (*s).chars().map(|x| x as u8).collect();
    let in_len:usize = s.len();
    let mut i:usize = 0;
    let mut pos_t:Vec<i32> = vec![];

    while i < in_len - 1 {
        if in_chars[i] == in_chars[i + 1] {
            let len = pos_t.len();
            if len < 2 {
                pos_t.push(i as i32);
            } else {
                pos_t[len - 1] = i as i32;
            }
        } else {
            if pos_t.is_empty() == false {
                let len = pos_t.len();
                if len < 2 {
                    pos_t.clear();
                    continue;
                }
                pos_t[len - 1] += 1;
                ret_vec.push(pos_t.clone());
                pos_t.clear();
            }
        }
        i += 1;
    }

    return ret_vec;
}
carloscn commented 1 year ago

code

https://github.com/carloscn/structstudy/commit/308c145ba1839befb376222f05d877bb88fb7278 https://review.gerrithub.io/c/carloscn/structstudy/+/550817