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:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
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
Java
public class Solution {
public int maxPower(String s) {
int maxPower = 1, currentPower = 1;
char previousChar = s.charAt(0);
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == previousChar) {
currentPower++;
} else {
maxPower = Math.max(maxPower, currentPower);
currentPower = 1;
previousChar = s.charAt(i);
}
}
maxPower = Math.max(maxPower, currentPower);
return maxPower;
}
}
Python
class Solution:
def maxPower(self, s: str) -> int:
max_power: int = 1
current_power: int = 1
previous_char: str = s[0]
for i in range(1, len(s)):
if s[i] == previous_char:
current_power += 1
else:
max_power = max(max_power, current_power)
current_power = 1
previous_char = s[i]
max_power = max(max_power, current_power)
return max_power
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.