문제 풀이/백준

[백준] 12891번. DNA 비밀번호

27200 2024. 1. 30. 00:03

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


문제


풀이

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        st = new StringTokenizer(br.readLine());
        int S = Integer.parseInt(st.nextToken());
        int P = Integer.parseInt(st.nextToken());

        String DNA = br.readLine();

        int[] countDNA = new int[4];
        st = new StringTokenizer(br.readLine());
        for(int i = 0; i < 4; i++){
            countDNA[i] = Integer.parseInt(st.nextToken());
        }

        int[] arr = new int[5];
        for(int i = 0; i < P; i++){
            if(DNA.substring(i,i+1).equals("A")){
                arr[0]++;
            }else if(DNA.substring(i,i+1).equals("C")){
                arr[1]++;
            }else if(DNA.substring(i,i+1).equals("G")){
                arr[2]++;
            }else if(DNA.substring(i,i+1).equals("T")){
                arr[3]++;
            }else{
                arr[4]++;
            }
        }

        int sum = 0;
        if(countDNA[0] <= arr[0] && countDNA[1] <= arr[2] && countDNA[2] <= arr[2] && countDNA[3] <= arr[3] && arr[4] == 0){
            sum++;
        }

        for(int i = 0; i < S - P; i++){
            if(DNA.substring(i,i+1).equals("A")){
                arr[0]--;
            }else if(DNA.substring(i,i+1).equals("C")){
                arr[1]--;
            }else if(DNA.substring(i,i+1).equals("G")){
                arr[2]--;
            }else if(DNA.substring(i,i+1).equals("T")){
                arr[3]--;
            }else{
                arr[4]--;
            }

            if(DNA.substring(i+P, i + P + 1).equals("A")){
                arr[0]++;
            }else if(DNA.substring(i+P, i + P + 1).equals("C")){
                arr[1]++;
            }else if(DNA.substring(i+P, i + P + 1).equals("G")){
                arr[2]++;
            }else if(DNA.substring(i+P, i + P + 1).equals("T")){
                arr[3]++;
            }else{
                arr[4]++;
            }

            if(countDNA[0] <= arr[0] && countDNA[1] <= arr[2] && countDNA[2] <= arr[2] && countDNA[3] <= arr[3]){
                sum++;
            }

        }

        System.out.println(sum);

    }

}

 

슬라이딩 윈도우 개념을 사용하여 풀이한 문제이다. 인덱스 설정에 유의해서 해결하면 될 것같다.