LeetCode - Consecutive Characters Solution - The Coding Shala

Home >> LeetCode >> Consecutive Characters

In this post, we will learn how to solve LeetCode's Consecutive Characters problem and will implement its Java Solution.

Consecutive Characters Problem

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 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.

Practice this problem on LeetCode: Click Here

Consecutive Characters Java Solution

Approach 1:
If two consecutive characters are the same then increase the count and return the maximum count of a char.

Java Program:

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

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Basic Structure of C++ Program - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Max Non Negative SubArray - The Coding Shala