본문 바로가기

백준

[백준] 9251 LCS [자바]

 


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

http://melonicedlatte.com/algorithm/2018/03/15/181550.html

 

[백준] 9251번 C/C++ 풀이 _ LCS - Easy is Perfect

출처 : https://www.acmicpc.net/problem/9251  시간 제한메모리 제한제출정답맞은 사람정답 비율1 초128 MB76453240240041.746% 문제LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때,

melonicedlatte.com

 

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class Main {
	static String str, str1;
	static Integer[][] dp;
 	public static void main(String arg[]) throws Exception {
 		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 		str = br.readLine();
 		str1 = br.readLine();
 		dp = new Integer[str.length()][str1.length()];
 		int result = LCS(str.length() - 1, str1.length() - 1);
 		System.out.println(result);
 	}
 	static int LCS(int x, int y) { //x == str y == str1
 		if(x == -1 || y == -1) {
 			return 0;
 		}
 		if(dp[x][y] != null)
 			return dp[x][y];
 		if(str.charAt(x) == str1.charAt(y)) {
 			return dp[x][y] = LCS(x-1, y-1) + 1;
 		}
 		else { //같지않다면 직전의 값(위, 왼쪽) 중 큰 값
 			return dp[x][y] = Math.max(LCS(x-1,y), LCS(x, y-1));
 		}
 	}
}

'백준' 카테고리의 다른 글

[백준] 9742 순열 [자바]  (0) 2022.03.02
[백준] 10827 a^b [자바]  (0) 2022.02.09
[백준] 15829 Hashing [자바]  (0) 2022.01.26
[백준] 3090 차이를 최소로 [자바]  (0) 2022.01.25
[백준] 2585 경비행기 [자바]  (0) 2022.01.19