Given a string s
, the task is to find the length of the longest contiguous substring of the same character.
Example:
s = "abbcccddddeeeeedcba"
5
Constraints:
1 <= s.length <= 500
s
consists of only lowercase English letters.No further clarifications needed. Let’s proceed to the solution strategy.
To find the length of the longest contiguous substring of the same character, we can maintain a counter that tracks the length of the current contiguous substring and another counter for the maximum length found so far:
max_length
to 1 (since the minimum length is 1).current_length
to 1 for the first character.current_length
.current_length
with max_length
and update max_length
if necessary, then reset current_length
to 1.current_length
one last time with max_length
.max_length
.def maxPower(s: str) -> int:
if not s:
return 0
max_length = 1
current_length = 1
for i in range(1, s.length):
if s[i] == s[i - 1]:
current_length += 1
else:
max_length = max(max_length, current_length)
current_length = 1
max_length = max(max_length, current_length)
return max_length
# Example usage
s = "abbcccddddeeeeedcba"
print(maxPower(s)) # Output is 5
The time complexity of this solution is O(n), where n is the length of the string s
. We iterate through the string once, making the solution efficient. The space complexity is O(1) as we use a constant amount of extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?