Consecutive Characters LeetCode Solution

Difficulty Level Easy
Frequently asked in Apple Google Microsoft YandexViews 3499

Problem Statement

Consecutive Characters LeetCode Solution – The power of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string s, return the power of s.

Consecutive Characters LeetCode Solution

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

Explanation

we need to find the Longest Substring with the same characters.

We can iterate over the given string, and use a variable count to record the length of that substring.

When the next character is the same as the previous one, we increase count by one. Else, we reset count to 1.

With this method, when reaching the end of a substring with the same characters, count will be the length of that substring, since we reset the count when that substring starts, and increase count when iterating that substring.

What do we need to do?

Increase the counter by 1 if the current char is the same as the previous one; otherwise, reset the counter to 1;

Update the max value of the counter during each iteration.

Why reset the counter to 1?

If the current char is not equal to the previous one then it means that more than one unique characters are present in the current substring, thus we reset the counter to 1 to recheck the following strings from now on.

Code

C++ Code for Consecutive Characters

class Solution {
public:
    int maxPower(string s) {
        // support variables
        int res = 0, i = 0, j, len = s.size(), curr = s[0];
        while (i < len) {
            // updating j
            j = i + 1;
            // moving j to the first value of s[j] != curr
            while (j < len && curr == s[j]) j++;
            // updating res
            res = max(res, j - i);
            // setting curr and i for the next loop
            curr = s[j];
            i = j;
        }
        return res;
    }
};

Java Code for Consecutive Characters

class Solution {
    public int maxPower(String s) {
         int ans = 1;
        for (int i = 1, cnt = 1; i < s.length(); ++i) {
            if (s.charAt(i) == s.charAt(i - 1)) {
                if (++cnt > ans) {
                    ans = cnt;
                }
            }else {
                cnt = 1;
            }
        }
        return ans;
    }
    
}

Python Code for Consecutive Characters

class Solution:
     def maxPower(self, s: str) -> int:
        cnt = ans = 1
        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                cnt += 1
                ans = max(cnt, ans)
            else:
                cnt = 1
        return ans

 

Complexity Analysis for Consecutive Characters LeetCode Solution

Time: O(n), Space: O(1), where n = s.length()

Reference: https://en.wikipedia.org/wiki/String_(computer_science)

Translate »