Similar Problems

Similar Problems not available

Consecutive Characters - Leetcode Solution

Companies:

LeetCode:  Consecutive Characters Leetcode Solution

Difficulty: Easy

Topics: string  

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.

Example:

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

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

Input: s = "triplepillooooow" Output: 5 Explanation: The substring "ooooo" is of length 5 with the character 'o' only.

Input: s = "hooraaaaaaaaaaay" Output: 11 Explanation: The substring "aaaaaaaaaaa" is of length 11 with the character 'a' only.

Solution:

The solution to this problem is quite simple. We will use two pointers, left and right, to traverse the string. We will also use two variables, maxLen and currLen, to keep track of the maximum length of consecutive characters we have seen so far and the length of the consecutive characters we are currently looking at.

We will initialize maxLen and currLen to 1 and left to 0. Then, we will iterate through the string using right pointer. If the current character equals the previous character, we will increment currLen. Otherwise, we will reset currLen to 1.

Finally, we will update maxLen if currLen is greater than maxLen. Once we have iterated through the entire string, we will return maxLen.

This algorithm has a time complexity of O(N), where N is the length of the string, as we only iterate through the string once.

Code:

Here is the Python implementation of the above algorithm:

class Solution: def maxPower(self, s: str) -> int: left = 0 maxLen = 1 currLen = 1

    for right in range(1, len(s)):
        if s[right] == s[right-1]:
            currLen += 1
        else:
            currLen = 1
            
        maxLen = max(maxLen, currLen)
        
    return maxLen

Conclusion: In this problem, we learned how to find the maximum length of a non-empty substring that contains only one unique character. We did this using a simple algorithm that uses two pointers and two variables to keep track of the maximum length and current length of consecutive characters we have seen so far.

Consecutive Characters Solution Code

1