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

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Single Number 2 LeetCode Solution - The Coding Shala