Problème
A probability lab flips a coin many times and writes the results as a string of H (heads) and T (tails). A streak is a maximal group of consecutive equal results; HHTHHH has the streaks HH, T and HHH. Students are often surprised how long the longest streak in a random record is, so the lab measures it.
Implement coin_toss_streaks(tosses).
Input
tosses: The results in order, using only H and T.
Output
Return [longest_heads, longest_tails, streaks]: the length of the longest heads streak, the length of the longest tails streak (0 if that side never comes up) and the total number of streaks.
Contraintes
0 ≤ length of tosses ≤ 100,000
Exemples
Entrée :
tosses = "HHTHHH"
Sortie attendue :
expected = [3, 1, 3]
Entrée :
std::string tosses = "HHTHHH";
Sortie attendue :
std::vector<long long> expected = {3, 1, 3};
Entrée :
string tosses = "HHTHHH";
Sortie attendue :
long[] expected = new long[] {3, 1, 3};
Explication
The streaks are HH, T and HHH, so the longest heads streak is 3, the longest tails streak is 1, and there are 3 streaks.
Entrée :
tosses = "TTTT"
Sortie attendue :
expected = [0, 4, 1]
Entrée :
std::string tosses = "TTTT";
Sortie attendue :
std::vector<long long> expected = {0, 4, 1};
Entrée :
string tosses = "TTTT";
Sortie attendue :
long[] expected = new long[] {0, 4, 1};
Explication
Heads never comes up, so its longest streak is 0; there is one tails streak of length 4: [0, 4, 1].
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
A new streak starts at index 0 and wherever a toss differs from the one before.
Indice 2
Keep one best length for heads and one for tails.
Indice 3
An empty string has no streaks at all.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.