본문 바로가기

백준

[백준] 9251 LCS (JAVA)

풀이

dp를 이용하여 푸는 문제이다 주의해야할점은 dp배열이 2차원이라는 것이다. 나는 아래의 블로그를 참고하였다.

 

https://st-lab.tistory.com/139

 

[백준] 9251번 : LCS - JAVA [자바]

www.acmicpc.net/problem/9251 9251번: LCS LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다. 예를 들어, ACAY..

st-lab.tistory.com

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {

    static char[] case1, case2;
    static Integer[][] dp;

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

        case1 = br.readLine().toCharArray();
        case2 = br.readLine().toCharArray();

        dp = new Integer[case1.length][case2.length];

        System.out.println(LCS(case1.length - 1, case2.length - 1));

    }

    static int LCS(int x, int y) {
        if (x == -1 || y == -1)
            return 0;

        if (dp[x][y] == null) {
            dp[x][y] = 0;

            if(case1[x] == case2[y]) dp[x][y] = LCS(x-1, y-1) + 1;
            else dp[x][y] = Math.max(LCS(x, y-1), LCS(x-1, y));
        }

        return dp[x][y];
    }
}