Problem
The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s
, return the power of s
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using counter
To solve this problem, we iterate through the string and keep track of the length of the current sequence of identical characters. We also maintain a variable for the maximum length found.
- Initialize Variables:
maxPower
to record the maximum length of a substring of identical characters.currentPower
to record the length of the current sequence of identical characters.previousChar
to keep track of the character in the current sequence.
- Iterate Through Characters:
- For each character in the string, if it matches
previousChar
, incrementcurrentPower
. - If it does not match, update
maxPower
ifcurrentPower
is larger, then resetcurrentPower
to 1 and updatepreviousChar
.
- For each character in the string, if it matches
- Final Update:
- After iterating through the string, ensure to update
maxPower
withcurrentPower
one last time to handle the end of the string.
- After iterating through the string, ensure to update
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the strings
, as we process each character once. - 🧺 Space complexity:
O(1)
since we use a constant amount of extra space for variables.