Problem Description
Given a string s, determine its "power"—the length of the longest contiguous substring that contains only one unique character. In other words, find the maximum number of consecutive identical characters in the string.
Key Insights
- The problem can be solved by scanning the string once.
- Keep track of the current streak of identical characters and update the maximum when the streak is broken or extended.
- A linear traversal yields an efficient O(n) solution.
Space and Time Complexity
Time Complexity: O(n) - where n is the length of the string, as we make one pass. Space Complexity: O(1) - uses only a few extra variables.
Solution
We use a simple iteration through the string to count consecutive characters. Two main variables are maintained: one for the current count of identical consecutive characters and one for the maximum count found so far. As we iterate, if the current character matches the previous one, the current count is incremented; otherwise, it is reset to 1. This method ensures we capture the longest substring of identical characters in one pass.