โจทย์
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.
เงื่อนไข
0 ≤ length of tosses ≤ 100,000
ตัวอย่าง
อินพุต:
tosses = "HHTHHH"
ผลลัพธ์ที่คาดหวัง:
expected = [3, 1, 3]
อินพุต:
std::string tosses = "HHTHHH";
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {3, 1, 3};
อินพุต:
string tosses = "HHTHHH";
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {3, 1, 3};
คำอธิบาย
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.
อินพุต:
tosses = "TTTT"
ผลลัพธ์ที่คาดหวัง:
expected = [0, 4, 1]
อินพุต:
std::string tosses = "TTTT";
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {0, 4, 1};
อินพุต:
string tosses = "TTTT";
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {0, 4, 1};
คำอธิบาย
Heads never comes up, so its longest streak is 0; there is one tails streak of length 4: [0, 4, 1].
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
A new streak starts at index 0 and wherever a toss differs from the one before.
คำใบ้ 2
Keep one best length for heads and one for tails.
คำใบ้ 3
An empty string has no streaks at all.
ความซับซ้อนที่คาดหวัง
O(n) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน