모든 챌린지
쉬움 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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.