Member-only story
Leetcode 1446: Consecutive Characters
1 min readMay 21, 2020
In this Leetcode problem, we count the maximum length of consecutive same character in a string.
Solution
Simply put here are the main ideas to resolve the problem:
- Go through the string remembering what character was last encountered
last
- Remember the current consecutive streak
current
- Remember the maximum number of consecutive same character encountered
max
- Be sure to handle edge cases correctly, such as empty string, one character string, strings only containing the same character (eg
“aaaaaaa”
)
Here is the full solution:
class Solution {
public int maxPower(String s) {
int n = s.length();
if (n < 2) {
return n;
}
char last = ' ';
int current = 0;
int max = 1;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == last) {
current++;
if (current > max) {
max = current;
}
} else {
current = 1;
last = c;
}
}
return max;
}
}
The algorithm is O(n) with n the length of the string, and O(1) space.
Happy coding :)
What’s next:
- Checkout the solution for another problem: Minimum time to collect all apples
- Contact me: poitevinpm@gmail.com
- Looking to interview for a software engineer position? Contact me :)