Skip to content

Commit 3eadf05

Browse files
committed
longest-common-subsequence solution
1 parent 4177b2f commit 3eadf05

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {string} text1
3+
* @param {string} text2
4+
* @return {number}
5+
*/
6+
var longestCommonSubsequence = function(text1, text2) {
7+
const resultMap = new Map();
8+
9+
const dfs = (i, j) => {
10+
const mapKey = `${i}-${j}`;
11+
12+
if (resultMap.has(mapKey)) {
13+
return resultMap.get(mapKey);
14+
}
15+
16+
if (i === text1.length || j === text2.length) {
17+
return 0;
18+
}
19+
20+
if (text1[i] === text2[j]) {
21+
const resultHit = 1 + dfs(i + 1, j + 1);
22+
resultMap.set(mapKey, resultHit);
23+
return resultHit;
24+
}
25+
26+
const resultMiss = Math.max(dfs(i + 1, j), dfs(i, j + 1));
27+
resultMap.set(mapKey, resultMiss);
28+
return resultMiss;
29+
}
30+
31+
return dfs(0, 0);
32+
};
33+
34+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(m * n) -> ์žฌ๊ท€๋ฅผ ํ†ตํ•ด m๊ณผ n์ด 1์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ์ƒ๋Œ€ํŽธ์˜ m or n ๋ฒˆ ์งธ ์ธ๋ฑ์Šค ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•˜๋ฏ€๋กœ??? (์ž˜ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค. ๋ฆฌ๋ทฐ์–ด๋ถ„์ด ์—ฌ์œ ๋˜์‹œ๋ฉด ์„ค๋ช…๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค ใ…œใ…œ)
35+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(m * n) -> ๋งต์— ํ‚ค๊ฐ€ m * n๊ฐœ๋กœ ์ตœ๋Œ€๋กœ ์š”์†Œ๊ฐ€ ๋“ค์–ด์˜ด

0 commit comments

Comments
ย (0)