Skip to content

Commit d9b9c42

Browse files
committed
add solution : 1143. Longest Common Subsequence
1 parent e7f87d0 commit d9b9c42

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

longest-common-subsequence/mmyeon.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @link https://leetcode.com/problems/longest-common-subsequence/description/
3+
*
4+
* 접근 방법 :
5+
* - LCS 길이 담을 DP 배열 선언
6+
* - 문자 순회하면서 같은 문자인 경우, 이전 값 + 1 로 업데이트
7+
* - 문자 다른 경우, 이전 값 그대로 유지
8+
*
9+
* 시간복잡도 : O(m * n)
10+
* - 두 문자열 길이 크기만큼 이중 반복문 실행
11+
*
12+
* 공간복잡도 : O(m * n)
13+
* - 두 문자 길이 크기만큼 DP 배열에 저장
14+
*/
15+
function longestCommonSubsequence(text1: string, text2: string): number {
16+
const m = text1.length,
17+
n = text2.length;
18+
19+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
20+
21+
for (let i = 1; i <= m; i++) {
22+
for (let j = 1; j <= n; j++) {
23+
if (text1[i - 1] === text2[j - 1]) {
24+
dp[i][j] = dp[i - 1][j - 1] + 1;
25+
} else {
26+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
27+
}
28+
}
29+
}
30+
return dp[m][n];
31+
}

0 commit comments

Comments
 (0)