Skip to content

Commit bf8f275

Browse files
committed
feat: longest common subsequence
1 parent 87fb4c0 commit bf8f275

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 시간 복잡도:
3+
* text1과 text2의 길이로 구성된 2차원 매트릭스를 순회하므로,
4+
* text1의 길이를 n, text2의 길이를 m이라고 하면 O(m*n)
5+
* 공간 복잡도:
6+
* text1과 text2의 길이로 구성된 2차원 매트릭스를 생성하므로, O(m*n)
7+
*/
8+
/**
9+
* @param {string} text1
10+
* @param {string} text2
11+
* @return {number}
12+
*/
13+
var longestCommonSubsequence = function(text1, text2) {
14+
const dp = new Array(text1.length+1).fill(0).map(e => new Array(text2.length+1).fill(0));
15+
for(let i = text1.length -1; i >= 0; i--) {
16+
for(let j = text2.length-1; j >=0; j--) {
17+
if(text1[i] === text2[j]) {
18+
dp[i][j] = dp[i+1][j+1] + 1
19+
} else {
20+
dp[i][j] = Math.max(dp[i+1][j], dp[i][j+1])
21+
}
22+
}
23+
}
24+
return dp[0][0]
25+
};

0 commit comments

Comments
 (0)