ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Coin Toss Streaks

Find the longest streak of heads, the longest streak of tails and the number of streaks in a coin toss record.

สิ่งที่คุณจะได้เรียนรู้

  • Split a sequence into maximal runs
  • Track the best run for each value
  • Count runs

โจทย์

ดูฉบับแปล

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

ตัวอย่างที่ 2
อินพุต:
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก