Skip to content

Commit 7040eef

Browse files
committed
add longest common subsequence solution
1 parent eacc99f commit 7040eef

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 두 문자열 text1과 text2가 주어질 때 가장 긴 공통 부분 수열의 길이를 리턴하고 없으면 0을 리턴하세요.
3+
*/
4+
class Solution {
5+
6+
// 시간복잡도: O(t1Length * t2Length)
7+
public int longestCommonSubsequence(String text1, String text2) {
8+
9+
int t1Length = text1.length();
10+
int t2Length = text2.length();
11+
12+
int[][]dp = new int[t1Length + 1][t2Length + 1];
13+
14+
for (int i = 1; i <= t1Length; i++) {
15+
for (int j = 1; j <= t2Length; j++) {
16+
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
17+
dp[i][j] = dp[i - 1][j - 1] + 1;
18+
} else {
19+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
20+
}
21+
}
22+
}
23+
return dp[t1Length][t2Length];
24+
25+
}
26+
}
27+

0 commit comments

Comments
 (0)