DEV Community

Sivakumar
Sivakumar

Posted on • Edited 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!!!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay