Consecutive Characters Problem
Description
LeetCode Problem 1446.
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.
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.
Constraints:
1 <= s.length <= 500sconsists of only lowercase English letters.
Solution
Approach: One Pass Over Runs
The power is the length of the longest run of one repeated character, so we only need to measure runs.
Walk through the string keeping run, the length of the block of equal characters that ends at the current position. If s[i] equals s[i - 1], the block grows by one; otherwise a new block starts and run goes back to 1. The answer is the largest run we see.
Both ans and run start at 1, because the string is never empty and its first character is already a run of length 1. This also covers a one-character string, where the loop does not run at all.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxPower(self, s: str) -> int:
ans = run = 1 # run: length of the block of equal characters ending at s[i]
for i in range(1, len(s)):
run = run + 1 if s[i] == s[i - 1] else 1
ans = max(ans, run)
return ans