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

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