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)){
                tmp++;
                if(tmp > ans) ans = tmp;
                continue;
            }
            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.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

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

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala