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:
maxPowerto record the maximum length of a substring of identical characters.currentPowerto record the length of the current sequence of identical characters.previousCharto 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
maxPowerifcurrentPoweris larger, then resetcurrentPowerto 1 and updatepreviousChar.
- For each character in the string, if it matches
- Final Update:
- After iterating through the string, ensure to update
maxPowerwithcurrentPowerone last time to handle the end of the string.
- After iterating through the string, ensure to update
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n)wherenis 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.