1. 문제

5525번: IOIOI



2. 개요

P1 = IOI

P2 = IOIOI

P3 = IOIOIOI

라고 할 때 주어진 S안에 Pn이 몇개 들어있는지 구하는 문제.



3. 풀이 및 코드

3-1. 풀이

최소단위인 IOI를 기준으로 첫 세자리부터 탐색한다.

만약 IOI라면 다음 I의 위치인 2만큼 이동하여 다시 탐색하며 길이를 1늘려준다.

아니라면 길이를 초기화시키고 한 칸 이동하여 맨 위부터 반복한다.

만약 길이가 Pn보다 크거나 같다면 답을 1만큼 늘려준다

문자열 탐색이 끝나고 답을 출력한다.

3-2. Python

import sys

N = int(sys.stdin.readline())
answer = 0

M = int(sys.stdin.readline())

S = sys.stdin.readline().rstrip()

idx = 0
length = 0
while idx <= M - 3:
    if S[idx: idx+3] == 'IOI':
        length += 1
        idx += 2

    else:
        length = 0
        idx += 1

    if length >= N:
        answer += 1

print(answer)

3-3. C#

namespace boj_5525
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());
            int M = int.Parse(Console.ReadLine());

            string S = Console.ReadLine().Trim();

            int answer = 0;

            int idx = 0;
            int length = 0;
            while (idx <= M - 3)
            {
                if (S.Substring(idx, 3) == "IOI")
                {
                    length++;
                    idx += 2;
                }

                else
                {
                    length = 0;
                    idx++;
                }

                if (length >= N)
                    answer++;
            }

            Console.WriteLine(answer);
        }
    }
}

Comments