Skip to content

Commit 2a99ebe

Browse files
committed
lcs solution
1 parent 26c990d commit 2a99ebe

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @param {string} text1
3+
* @param {string} text2
4+
* @return {number}
5+
*
6+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(m * n)
7+
* - m = text1.length, n = text2.length
8+
* - 2์ค‘ for๋ฌธ์œผ๋กœ dp ํ…Œ์ด๋ธ” ์ฑ„์šฐ๊ธฐ
9+
*
10+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(m * n)
11+
* - dp ๋ฐฐ์—ด์— m * n ๋งŒํผ์˜ ๊ณต๊ฐ„ ์‚ฌ์šฉ
12+
* - ์ตœ์ ํ™”ํ•˜๋ ค๋ฉด ๋ฐฐ์—ด 2๊ฐœ๋กœ๋„ ๊ฐ€๋Šฅ
13+
*/
14+
var longestCommonSubsequence = function(text1, text2) {
15+
let m = text1.length;
16+
let n = text2.length;
17+
18+
// 2์ฐจ์› dp ๋ฐฐ์—ด ์ดˆ๊ธฐํ™” (m+1) x (n+1)
19+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
20+
21+
// dp[i][j] = text1[0..i-1], text2[0..j-1] ๊นŒ์ง€์˜ LCS ๊ธธ์ด
22+
for (let i = 1; i <= m; i++) {
23+
for (let j = 1; j <= n; j++) {
24+
if (text1[i - 1] === text2[j - 1]) {
25+
// ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด, ์ด์ „๊นŒ์ง€์˜ LCS + 1
26+
dp[i][j] = dp[i - 1][j - 1] + 1;
27+
} else {
28+
// ์•„๋‹ˆ๋ฉด, ์ด์ „ ํ–‰/์—ด ์ค‘ ๋” ํฐ ๊ฐ’ ์„ ํƒ
29+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
30+
}
31+
}
32+
}
33+
34+
return dp[m][n]; // ๋งˆ์ง€๋ง‰ cell์ด ์ •๋‹ต
35+
};
36+
37+
//์‹คํŒจํ•œ dfs ์ฝ”๋“œ
38+
/**
39+
* @param {string} text1
40+
* @param {string} text2
41+
* @return {number}
42+
*/
43+
var longestCommonSubsequence = function(text1, text2) {
44+
function dfs(i, j) {
45+
// ์ข…๋ฃŒ ์กฐ๊ฑด: ์ธ๋ฑ์Šค ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด 0
46+
if (i === text1.length || j === text2.length) {
47+
return 0;
48+
}
49+
50+
// ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด, ๋‹ค์Œ ๋ฌธ์ž๋กœ ์ด๋™ํ•˜๋ฉฐ ๊ธธ์ด +1
51+
if (text1[i] === text2[j]) {
52+
return 1 + dfs(i + 1, j + 1);
53+
}
54+
55+
// ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅด๋ฉด, ๋‘ ๊ฐ€์ง€ ๊ฐˆ๋ž˜ ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ์„ ํƒ
56+
return Math.max(
57+
dfs(i + 1, j), // text1์˜ ๋‹ค์Œ ๋ฌธ์ž๋กœ
58+
dfs(i, j + 1) // text2์˜ ๋‹ค์Œ ๋ฌธ์ž๋กœ
59+
);
60+
}
61+
62+
return dfs(0, 0);
63+
};

0 commit comments

Comments
ย (0)