Skip to content

Commit c523446

Browse files
authored
[ PS ] : Longest Common Subsequence
1 parent 558ed4e commit c523446

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 가장 긴 공통 부분 수열의 길이를 반환하는 함수
3+
* @param {string} text1
4+
* @param {string} text2
5+
* @return {number}
6+
*/
7+
const longestCommonSubsequence = function (text1, text2) {
8+
const dp = Array.from({ length: text1.length }, () => Array.from({ length: text2.length }, () => -1));
9+
10+
// text1, 2를 순회하는 포인터 i, j를 두고, 두 문자끼리 비교하는 함수
11+
function dfs(i, j) {
12+
// 포인터가 범위를 넘어가면 백트래킹
13+
if (i === text1.length || j === text2.length) {
14+
return 0;
15+
}
16+
17+
// 두 문자를 이미 비교한 적 있는 경우 해당 결과 반환
18+
if (dp[i][j] !== -1) {
19+
return dp[i][j];
20+
}
21+
22+
// 두 문자를 비교
23+
if (text1[i] === text2[j]) {
24+
dp[i][j] = 1 + dfs(i + 1, j + 1);
25+
} else {
26+
dp[i][j] = Math.max(dfs(i + 1, j), dfs(i, j + 1));
27+
}
28+
29+
return dp[i][j];
30+
}
31+
32+
return dfs(0, 0);
33+
};
34+
35+
// 시간복잡도: O(m * n) (m: text1.length, n: text2.length)
36+
// 공간복잡도: O(m * n) (재귀 호출 깊이: m + n, dp 배열 크기: m * n)

0 commit comments

Comments
 (0)