carloscn / structstudy

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

leetcode1446:连续字符(consecutive-characters) #229

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。

请你返回字符串 s 的 能量。

  示例 1:

输入:s = "leetcode" 输出:2 解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。

示例 2:

输入:s = "abbcccddddeeeeedcba" 输出:5 解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。  

提示:

1 <= s.length <= 500 s 只包含小写英文字母。

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/consecutive-characters

carloscn commented 1 year ago

问题分析

pub fn max_power(s: String) -> i32
{
    if s.is_empty() {
        return 0;
    }

    let mut count:i32 = 1;
    let mut max_count:i32 = 0;
    let s_vec:Vec<char> = s.chars().collect();

    for i in 0..s_vec.len() - 1 {
        if s_vec[i] == s_vec[i + 1] {
            count += 1;
        } else {
            max_count = max_count.max(count);
            count = 1;
        }
    }

    return max_count;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/554267 https://github.com/carloscn/structstudy/commit/6fe2361fa8effe316a72ae6a51f3b152b241e580