Leetcode 1446. Consecutive Characters
Given a string s
, the task is to find the length of the longest substring containing only one unique character.
s
composed only of lowercase/uppercase English letters?The problem requires finding the length of the longest contiguous substring that contains the same character. Here’s a step-by-step strategy to solve this problem:
maxLength
to keep track of the maximum length found.currentChar
to track the current character being considered.currentLength
to track the length of the current sequence of identical characters.currentChar
, increase the currentLength
.maxLength
if currentLength
is greater, and then reset currentChar
and currentLength
.maxLength
.Here’s how you can implement the above strategy in C++:
#include <string>
#include <algorithm>
class Solution {
public:
int maxPower(std::string s) {
if (s.empty()) return 0;
int maxLength = 1; // At least one character long sequence exists
int currentLength = 1;
char currentChar = s[0];
for (int i = 1; i < s.length(); ++i) {
if (s[i] == currentChar) {
currentLength++;
} else {
maxLength = std::max(maxLength, currentLength);
currentChar = s[i];
currentLength = 1;
}
}
// Final comparison to catch sequences at the end of the string
maxLength = std::max(maxLength, currentLength);
return maxLength;
}
};
The time complexity of this solution is O(n), where n
is the length of the string s
. This is because we only need to pass through the string once, performing constant-time operations at each step.
The space complexity is O(1) since we are using only a fixed amount of extra space regardless of the input size.
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?