본문 바로가기
코딩일기

[알고리즘] 백준#12891 DNA 비밀번호 - C#

by 심다린 2025. 5. 7.

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

 

 

 

이 문제는 윈도우 슬라이딩을 이용해서 해결해야하는 문제이다.

개념은 아주 간단하다.

문제에서 제시한 P 만큼의 구간을 정해놓고 배열 내에서 움직여 가며 만들 수 있는 비밀번호의 종류의 수를 찾는 것이다.

 

그리고 문제의 핵심은 조건으로 주어진 A,C,G,T의 개수를 저장해놓는 배열을 만들고,

현재 문자열의 A,C,G,T 개수를 저장하여 수를 비교하면서 비밀번호를 만들 수 있는지 없는지 판단하는 것이다 .

 

<나의 풀이>

using System;
namespace CodingTest.Baekjoon
{
    //DNA 비밀번호
    public class B_12891
    {
        public static void Main(string[] args)
        {
            string[] firstLine = Console.ReadLine().Split(' ');
            int S = int.Parse(firstLine[0]);
            int P = int.Parse(firstLine[1]);

            string DNA = Console.ReadLine();

            int[] myArr = new int[4];
            int[] checkArr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse) ;

            int validCount = 0;

            for (int i = 0; i < P; i++)
            {
                AddChar(DNA[i], myArr);
            }

            if (isValid(myArr, checkArr))
                validCount++;

            for (int i = P; i < S; i++)
            {
                AddChar(DNA[i], myArr);
                Remove(DNA[i - P], myArr);
                if (isValid(myArr, checkArr))
                    validCount++;
            }

            Console.WriteLine(validCount);
        }

        static void AddChar(char c, int[] myArr)
        {
            switch (c)
            {
                case 'A': myArr[0]++; break;
                case 'C': myArr[1]++; break;
                case 'G': myArr[2]++; break;
                case 'T': myArr[3]++; break;
            }
        }

        static void Remove(char c, int[] myArr)
        {
            switch (c)
            {
                case 'A': myArr[0]--; break;
                case 'C': myArr[1]--; break;
                case 'G': myArr[2]--; break;
                case 'T': myArr[3]--; break;
            }
        }

        static bool isValid(int[] myArr, int[] checkArr)
        {
            for (int i = 0; i < 4; i++)
            {
                if (myArr[i] < checkArr[i])
                    return false;
            }
            return true;
        }
    }
}