Consecutive Characters

Updated on 19 May, 2025
Consecutive Characters header image

Problem Statement

The concept of the power of a string refers to the length of the longest contiguous segment (or substring) within the string that contains exactly one unique character. Given a string s, the task is to calculate its power. This involves identifying the longest substring where the same single character repeats consecutively without any interruption of a different character.

Examples

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.

Constraints

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

Approach and Intuition

To solve this problem, we aim to find the maximum length of a substring which is composed entirely of the same character. The approach involves iterating through the string s while maintaining a count of consecutive characters. Here's a step-by-step breakdown:

  1. Initialize two variables: max_power to store the maximum length of such substrings and current_power to count consecutive characters as you traverse the string.
  2. Iterate through the string from the first character to the last.
  3. Compare each character with the previous one:
    • If they are the same, increment the current_power.
    • If they are different, update max_power if current_power is greater, and reset current_power to 1 (since the new different character starts its own potential substring).
  4. After the loop, there might be a case where the longest substring is at the end of the string. Therefore, compare and potentially update max_power with current_power one last time.
  5. The value of max_power at the end of these steps will be the power of the string.

Below are the example walkthroughs based on the given examples:

  • Example 1: "leetcode"
    • The contiguous repeats of 'e' form the longest substrings of the same character, and the length is 2.
  • Example 2: "abbcccddddeeeeedcba"
    • The sequence of 'e' repeated five times consecutively forms the longest such segment with a length of 5.

These insights showcase how to tackle the problem by focusing on consecutive characters and ensure the solution adheres to the constraints that the input string length will not exceed 500 characters, and only lowercase English letters are included.

Solutions

  • Java
  • Python
java
class Solution {
    public int longestRepetition(String str) {
        int currentCount = 0;
        int maximumCount = 0;
        char lastChar = ' ';
        for (int index = 0; index < str.length(); index++) {
            char currentChar = str.charAt(index);
            if (currentChar == lastChar) {
                currentCount++;
            } else {
                currentCount = 1;
                lastChar = currentChar;
            }
            maximumCount = Math.max(maximumCount, currentCount);
        }
        return maximumCount;
    }
}

This code in Java defines a function longestRepetition that determines the length of the longest contiguous block of repeating characters in a given string. The function works as follows:

  • Initialize two counters, currentCount and maximumCount, to zero. currentCount keeps track of the current sequence length, and maximumCount stores the maximum sequence length found.
  • Use a character variable, lastChar, initialized to a space character, to remember the last character processed.
  • Iterate through each character in the input string using a for loop.
  • Within the loop, compare the current character with lastChar. If they match, increment currentCount. If not, reset currentCount to 1 and update lastChar to the current character.
  • Update maximumCount with the larger of maximumCount or currentCount using Math.max.
  • Return maximumCount after the loop completes, which represents the length of the longest sequence of identical consecutive characters in the string.

This function efficiently computes the desired result by making a single pass through the string, maintaining a constant space complexity, and providing an O(n) time complexity, where n is the length of the string.

python
class Solution:
    def longest_sequence(self, string: str) -> int:
        current_length = 0
        longest_length = 0
        last_char = None
        for char in string:
            if char == last_char:
                current_length += 1
            else:
                last_char = char
                current_length = 1
            longest_length = max(longest_length, current_length)
        return longest_length

The provided Python code helps in determining the length of the longest contiguous sequence of identical characters in a given string. Here's a concise solution summary:

  • Define a method longest_sequence which accepts a string parameter.
  • Initialize variables current_length, longest_length, and last_char to keep track of the ongoing length of a sequence, the maximum length found, and the last character processed, respectively.
  • Iteratively process each character in the provided string:
    • If the current character is the same as the last one, increment the current_length.
    • If not, update last_char to the current character, and reset current_length to 1.
    • Continuously update longest_length with the maximum of its current value or current_length.
  • Return longest_length which contains the longest sequence found.

This approach ensures efficient computation by processing the string in a single pass.

Comments

No comments yet.