DEV Community

Sivakumar
Sivakumar

Posted on • Updated on

Data Structures & Algorithms using Rust: Consecutive Characters

As part of Data Structures & Algorithms implementation using Rust, let's see how to solve Consecutive Characters problem.

Leetcode problem link: https://leetcode.com/problems/consecutive-characters/

Problem Statement
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.

Return the power of the string.
Enter fullscreen mode Exit fullscreen mode
Instructions
Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:

Input: s = "triplepillooooow"
Output: 5

Example 4:

Input: s = "hooraaaaaaaaaaay"
Output: 11

Example 5:

Input: s = "tourist"
Output: 1

Constraints:

1 <= s.length <= 500
s contains only lowercase English letters.
Enter fullscreen mode Exit fullscreen mode
Solution

Please find below the solution implemented using Rust

impl Solution {
    pub fn max_power(s: String) -> i32 {
        let mut ch: char = ' ';
        let mut i1: i32 = 1;
        let mut max: i32 = 1;
        for (i, c) in s.chars().enumerate() {
            if c != ch {
                ch = c;
                if i1 > max {
                    max = i1;
                }
                i1 = 1;
            } else {
                i1 += 1;
            }
        }
        if i1 > max {
            max = i1;
        }
        max
    }
}
Enter fullscreen mode Exit fullscreen mode

Please feel free to share your feedback.

Happy reading!!!

Top comments (0)