Consecutive Characters
The following code returns the power of the given string s
, which is defined as the maximum length of a non-empty substring containing only one unique character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| class Solution:
def maxPower(self, s: str) -> int:
# Initialize variables to keep track of the current character, its count, and the maximum count
current_char = s[0]
current_count = 1
max_count = 1
# Iterate through the string starting from the second character
for i in range(1, len(s)):
# Check if the character is the same as the current character
if s[i] == current_char:
# Increment the current count
current_count += 1
else:
# If the character is different, update the current character and reset the current count
current_char = s[i]
current_count = 1
# Update the maximum count if the current count is higher
if current_count > max_count:
max_count = current_count
return max_count
|
The code initializes variables to keep track of the current character, its count, and the maximum count. It then iterates through the string starting from the second character, updating the counts based on whether the current character is the same or different from the previous one.
The time complexity of this solution is O(n), and the space complexity is O(1), where n is the length of the input string.