Skip to content

Commit 2517fa1

Browse files
committed
longest-common-subsequence solution
1 parent e34fe26 commit 2517fa1

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}

0 commit comments

Comments
 (0)