BOJ 9251 LCS
BOJ 9251 LCS
https://www.acmicpc.net/problem/9251
문제
LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다.
예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.
입력
첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다.
출력
첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를 출력한다.
예제 입력 1
ACAYKP CAPCAK
예제 출력 1
4
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] input1 = br.readLine().toCharArray(), input2 = br.readLine().toCharArray();
int[][] lcs = new int[input1.length + 1][input2.length + 1];
for (int i = 0; i < input1.length; i++) {
for (int j = 0; j < input2.length; j++) {
if(input1[i] == input2[j]) lcs[i + 1][j + 1] = lcs[i][j] + 1;
else lcs[i + 1][j + 1] = Integer.max(lcs[i][j + 1], lcs[i + 1][j]);
}
}
System.out.println(lcs[input1.length][input2.length]);
}
}
This post is licensed under CC BY 4.0 by the author.