File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 알고달레 풀이 참고해서 풀었습니다.
3
+ * @see https://www.algodale.com/problems/longest-common-subsequence/
4
+ *
5
+ * DP + 2차원 배열을 이용한 풀이
6
+ * 행은 text1, 열은 text2에 대응하고
7
+ * index는 text의 처음부터 몇개 문자를 사용할건지 의미합니다.
8
+ * 마지막 문자가 동일하다면 dp[index1][index2] = dp[index1 - 1][index2 - 1] + 1
9
+ * 마지막 문자가 다르다면 dp[index1][index2] = Math.max(dp[index1 - 1][index2], dp[index1][index2 - 1])
10
+ *
11
+ * TC: O(T1 * T2)
12
+ * 2차원 배열을 순회
13
+ *
14
+ * SC: O(T1 * T2)
15
+ * 2차원 배열 생성
16
+ *
17
+ * T1: text1.length, T2: text2.length
18
+ */
19
+
20
+ /**
21
+ * @param {string } text1
22
+ * @param {string } text2
23
+ * @return {number }
24
+ */
25
+ var longestCommonSubsequence = function ( text1 , text2 ) {
26
+ const LENGTH1 = text1 . length ;
27
+ const LENGTH2 = text2 . length ;
28
+ const memory = Array . from ( { length : LENGTH1 + 1 } , ( ) =>
29
+ Array . from ( { length : LENGTH2 + 1 } , ( ) => 0 )
30
+ ) ;
31
+
32
+ for ( let index1 = 1 ; index1 <= LENGTH1 ; index1 ++ ) {
33
+ for ( let index2 = 1 ; index2 <= LENGTH2 ; index2 ++ ) {
34
+ if ( text1 [ index1 - 1 ] === text2 [ index2 - 1 ] ) {
35
+ memory [ index1 ] [ index2 ] = memory [ index1 - 1 ] [ index2 - 1 ] + 1 ;
36
+ } else {
37
+ memory [ index1 ] [ index2 ] = Math . max (
38
+ memory [ index1 - 1 ] [ index2 ] ,
39
+ memory [ index1 ] [ index2 - 1 ]
40
+ ) ;
41
+ }
42
+ }
43
+ }
44
+
45
+ return memory [ LENGTH1 ] [ LENGTH2 ] ;
46
+ } ;
You can’t perform that action at this time.
0 commit comments