Consecutive Characters
Problem
The power of a string is the maximum length of a non-empty substring that contains only one unique character. Given a string s of lowercase letters, return the power of s — that is, the length of its longest run of identical characters.
s = "abbcccddddeeeeedcba"5def maxPower(s):
best = 1 # longest run seen so far
cur = 1 # length of the current run
for i in range(1, len(s)):
if s[i] == s[i - 1]: # same char extends the run
cur += 1
best = max(best, cur)
else: # different char resets the run
cur = 1
return best
function maxPower(s) {
let best = 1; // longest run seen so far
let cur = 1; // length of the current run
for (let i = 1; i < s.length; i++) {
if (s[i] === s[i - 1]) { // same char extends the run
cur += 1;
best = Math.max(best, cur);
} else { // different char resets the run
cur = 1;
}
}
return best;
}
int maxPower(String s) {
int best = 1; // longest run seen so far
int cur = 1; // length of the current run
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) { // same char extends
cur += 1;
best = Math.max(best, cur);
} else { // different char resets the run
cur = 1;
}
}
return best;
}
int maxPower(string s) {
int best = 1; // longest run seen so far
int cur = 1; // length of the current run
for (int i = 1; i < (int)s.size(); i++) {
if (s[i] == s[i - 1]) { // same char extends the run
cur += 1;
best = max(best, cur);
} else { // different char resets the run
cur = 1;
}
}
return best;
}
Explanation
A substring of a single repeated character is just a run — a maximal block of equal letters. The power of the string is the length of its longest run, so we never need to look at every substring; one linear scan is enough.
We keep two counters. cur is the length of the run ending at the current index, and best is the longest run we have completed so far. Both start at 1 because the first character alone is already a run of length one, and the string is guaranteed non-empty.
Walking from index 1 to the end, we compare each character with the one before it. If they are equal, the current run grows by one, so we do cur += 1 and refresh best = max(best, cur). If they differ, the run is broken and a new run starts at this character, so we reset cur = 1.
Because best is updated every time the run extends, by the end it holds the maximum run length anywhere in the string — exactly the power we return.
Example: "abbcccddddeeeeedcba" has runs of lengths 1, 2, 3, 4, 5, then singletons. The longest is the block of five es, so the answer is 5.