3773. Maximum Number of Equal Length Runs π
Description
You are given a string s consisting of lowercase English letters.
A run in s is a substring of equal letters that cannot be extended further. For example, the runs in "hello" are "h", "e", "ll", and "o".
You can select runs that have the same length in s.
Return an integer denoting the maximum number of runs you can select in s.
Example 1:
Input: s = "hello"
Output: 3
Explanation:
The runs in s are "h", "e", "ll", and "o". You can select "h", "e", and "o" because they have the same length 1.
Example 2:
Input: s = "aaabaaa"
Output: 2
Explanation:
The runs in s are "aaa", "b", and "aaa". You can select "aaa" and "aaa" because they have the same length 3.
Constraints:
1 <= s.length <= 105sconsists of lowercase English letters only.
Solutions
Solution 1: Hash Table
Thinking
We may keep only runs of one common length, so the answer is the most frequent run length. One groupby pass counts lengths and we take the maximum frequency.
We can use a hash table \(\textit{cnt}\) to record the number of occurrences of each run length. We traverse the string \(s\), and for each run, we calculate its length \(m\) and increment \(\textit{cnt}[m]\) by \(1\). Finally, the answer is the maximum value in \(\textit{cnt}\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the string \(s\).
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |