코딩 테스트/백준

[백준][gold5] 9251번: LCS - JAVA

갓생사는 김초원의 개발 블로그 2021. 5. 9. 15:49

[문제]

www.acmicpc.net/problem/9251

 

9251번: LCS

LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다. 예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.

www.acmicpc.net

 

대학교 알고리즘 수업때 들었지만 기억이 가물가물했다. 

아래 유튜브를 보면서 다시 공부했다. 

www.youtube.com/watch?v=EAXDUxVYquY

 

[코드]

package com.algorithm.baekjoon.gold5;

import java.io.*;

/**
 * 9251 - LCS
 */
public class Test04 {
    public static int[][] LCS;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String X = br.readLine();
        String Y = br.readLine();

        int xLen = X.length();
        int yLen = Y.length();

        LCS = new int[xLen + 1][yLen + 1];

        getLCS(X, Y);
        bw.write(LCS[xLen][yLen] + "\n");

        br.close();
        bw.flush();
        bw.close();
    }

    public static void getLCS(String X, String Y) {
        for (int i = 1; i < LCS.length; i++) {
            for (int j = 1; j < LCS[0].length; j++) {
                if (X.charAt(i - 1) == Y.charAt(j - 1)) {
                    LCS[i][j] = LCS[i - 1][j - 1] + 1;
                } else {
                    LCS[i][j] = Math.max(LCS[i - 1][j], LCS[i][j - 1]);
                }
            }
        }
    }
}