Skip to content

Commit a91dd42

Browse files
committed
add: solve #274 Longest Common Subsequence with ts
1 parent 949845f commit a91dd42

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* ๋‘ ๋ฌธ์ž์—ด์˜ ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ.
3+
*
4+
* @param {string} text1 - ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž์—ด
5+
* @param {string} text2 - ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž์—ด
6+
* @returns {number} - ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
7+
*
8+
* ์‹œ๊ฐ„ ๋ณต์žก๋„:
9+
* - O(m * n) : ๋‘ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๊ฐ๊ฐ m, n์ด๋ผ๊ณ  ํ•  ๋•Œ, DP ํ…Œ์ด๋ธ”์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.
10+
*
11+
* ๊ณต๊ฐ„ ๋ณต์žก๋„:
12+
* - O(m * n) : m+1 x n+1 ํฌ๊ธฐ์˜ 2์ฐจ์› DP ํ…Œ์ด๋ธ”์„ ์ƒ์„ฑํ•˜์—ฌ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
13+
*/
14+
function longestCommonSubsequence(text1: string, text2: string): number {
15+
const m = text1.length;
16+
const n = text2.length;
17+
18+
// DP ํ…Œ์ด๋ธ” ์ƒ์„ฑ (m+1 x n+1 ํฌ๊ธฐ)
19+
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
20+
21+
// DP ๊ณ„์‚ฐ
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+
// ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•˜๋ฉด ์ด์ „ ๊ฐ’์— +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+
// ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
35+
return dp[m][n];
36+
}
37+

0 commit comments

Comments
ย (0)