File tree Expand file tree Collapse file tree
longest-common-subsequence Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int longestCommonSubsequence (String text1 , String text2 ) {
3+ /**
4+ 1.문제: 가장 긴 common subsequence length return, 없으면 0 return
5+ 2.constraints
6+ - length min = 1, max = 1000
7+ - text1, text2 모두 lowercase로 구성
8+ 3.풀이
9+ - dp[i][j] = text1의 앞 i개, text2의 앞 j개를 비교했을 때 LCS 길이
10+ - 문자가 같으면: dp[i][j] = dp[i-1][j-1] + 1
11+ - 문자가 다르면: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
12+ */
13+ int t1Size = text1 .length (); //row
14+ int t2Size = text2 .length (); //col
15+ int [][] dp = new int [t1Size + 1 ][t2Size + 1 ];
16+
17+ for (int i = 1 ; i <= t1Size ; i ++) {
18+ for (int j = 1 ; j <= t2Size ; j ++) {
19+ if (text1 .charAt (i -1 ) == text2 .charAt (j -1 )) {
20+ dp [i ][j ] = dp [i -1 ][j -1 ] + 1 ;
21+ } else {
22+ dp [i ][j ] = Math .max (dp [i -1 ][j ], dp [i ][j -1 ]);
23+ }
24+ }
25+ }
26+ return dp [t1Size ][t2Size ];
27+ }
28+ }
You can’t perform that action at this time.
0 commit comments