https://www.acmicpc.net/problem/5525

 

5525번: IOIOI

N+1개의 I와 N개의 O로 이루어져 있으면, I와 O이 교대로 나오는 문자열을 PN이라고 한다. P1 IOI P2 IOIOI P3 IOIOIOI PN IOIOI...OI (O가 N개) I와 O로만 이루어진 문자열 S와 정수 N이 주어졌을 때, S안에 PN이 몇

www.acmicpc.net

접근 방법

1. IO를 n의 개수만큼 반복 +I를 한 io문자열과 입력받은 문자열 S를 반복문으로 돌며 substring하고 서로 비교 - 50점

2. 문자열을 자르지 않고, 카운트를 사용해서 i, i+1, i+2 번째를 계속 비교하며 더해줌 - 인덱스 오류나서 포기

3. 큐에 I의 인덱스를 집어넣고 그 차이가 2이면 카운트를 올리고 n 이상이면 ans++, 차이가 2가 아니면 카운트를 다시 0으로 -100점

 

문제 풀이

100점 짜리 문제만 풀이

  • I 가 나온 위치의 인덱스를 큐에 저장
  • 큐에서 하나 리턴 - 이전 I의 인덱스, 반복문을 돌림
  • peek와 이전 I의 인덱스가 2이면 IOI 라는 소리니 카운트+1
  • 2가 아니면 끊어졌으므로 카운트는 다시 0
  • 만약 카운트의 값이 n이상이면 ans에 1을 더해줌 - (==가 아닌 >= 인 이유 : 연속적으로 나오는 것이 있어서)
  • 이전 I의 인덱스를 갱신

 

50점

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Baekjoon.silver
{
    class _5525
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int len = int.Parse(Console.ReadLine());
            string s = Console.ReadLine();
            string io = string.Concat(Enumerable.Repeat("IO", n)) + "I";
            //Console.WriteLine(io);

            int iolen = io.Length;
            int ans = 0;
            for(int i = 0; i<len-iolen; i++)
            {
                string s2 = s.Substring(i, iolen);
                if (s2 == io)
                    ans++;
            }
            Console.WriteLine(ans);
        }
    }
}

 

100점

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Baekjoon.silver
{
    class _5525
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int len = int.Parse(Console.ReadLine());
            string s = Console.ReadLine();
            //string io = string.Concat(Enumerable.Repeat("IO", n)) + "I";
            //Console.WriteLine(io);

            Queue<int> que = new Queue<int>();
            for(int i = 0; i<len; i++)
            {
                if (s[i] == 'I')
                    que.Enqueue(i);
            }

            int ans = 0;
            int temp = que.Dequeue(); //이전 I인덱스
            int count = 0;
            while (que.Count > 0)
            {
                if (que.Peek() - temp == 2)
                    count++;
                else
                    count = 0;

                if (count >= n)
                    ans++;

                temp = que.Dequeue();
            }

            Console.WriteLine(ans);
        }
    }
}

'문제 풀이 > C#' 카테고리의 다른 글

[25597] - 푸앙이와 러닝머신  (0) 2022.11.15
[18352] - 특정 거리의 도시 찾기  (0) 2022.11.14
[11286] - 절댓값 힙  (0) 2022.11.09
[1074] - Z  (0) 2022.11.08
[5397] - 키로거  (0) 2022.11.07

+ Recent posts