Skip to content

Commit ed81cb1

Browse files
committed
Longest Common Subsequence Solution
1 parent bb9b733 commit ed81cb1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 두 문자열에서 공통으로 나타나는 부분 수열 중 가장 긴 것의 길이를 찾는 문제
3+
*
4+
* 다이나믹 프로그래밍(DP): 작은 문제의 결과를 저장해서 큰 문제를 해결하는 방법
5+
* 시간 복잡도: O(m × n)
6+
* 공간복잡도: O(min(m, n))
7+
*/
8+
/**
9+
* @param {string} text1
10+
* @param {string} text2
11+
* @return {number}
12+
*/
13+
var longestCommonSubsequence = function (text1, text2) {
14+
// 더 짧은 문자열을 text2로 만들어 공간 절약
15+
if (text1.length < text2.length) {
16+
[text1, text2] = [text2, text1];
17+
}
18+
19+
const m = text1.length;
20+
const n = text2.length;
21+
22+
// 1차원 배열 2개만 사용 (이전 행, 현재 행)
23+
let prev = Array(n + 1).fill(0);
24+
let curr = Array(n + 1).fill(0);
25+
26+
for (let i = 1; i <= m; i++) {
27+
for (let j = 1; j <= n; j++) {
28+
if (text1[i - 1] === text2[j - 1]) {
29+
curr[j] = prev[j - 1] + 1;
30+
} else {
31+
curr[j] = Math.max(prev[j], curr[j - 1]);
32+
}
33+
}
34+
// 다음 반복을 위해 배열 교체
35+
[prev, curr] = [curr, prev];
36+
curr.fill(0);
37+
}
38+
39+
return prev[n];
40+
};

0 commit comments

Comments
 (0)