Leetcode 1446. Consecutive Characters
Leetcode 1446 - Consecutive Characters
Given a string s
, the task is to find the length of the longest contiguous substring of the same character.
s = "abbcccddddeeeeedcba"
5
s
be empty?
1
, as the longest sequence of identical characters will be any individual character.s
?
s
.maxLength
: the longest length of consecutive characters found so far.currentLength
: the current length of the ongoing sequence of identical characters.currentLength
.maxLength
if currentLength
is greater, and reset currentLength
to 1.maxLength
one final time in case the longest sequence is at the end of the string.public int maxPower(String s) {
// Edge case: if the string is empty.
if (s == null || s.length() == 0) {
return 0;
}
int maxLength = 1;
int currentLength = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
currentLength++;
} else {
maxLength = Math.max(maxLength, currentLength);
currentLength = 1;
}
}
// Final comparison after the loop
maxLength = Math.max(maxLength, currentLength);
return maxLength;
}
n
is the length of the string s
.
This solution provides an efficient and clear method to determine the length of the longest contiguous substring of the same character in a given string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?