File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @link https://leetcode.com/problems/longest-common-subsequence/description/
3
+ *
4
+ * 접근 방법 :
5
+ * - LCS 길이 담을 DP 배열 선언
6
+ * - 문자 순회하면서 같은 문자인 경우, 이전 값 + 1 로 업데이트
7
+ * - 문자 다른 경우, 이전 값 그대로 유지
8
+ *
9
+ * 시간복잡도 : O(m * n)
10
+ * - 두 문자열 길이 크기만큼 이중 반복문 실행
11
+ *
12
+ * 공간복잡도 : O(m * n)
13
+ * - 두 문자 길이 크기만큼 DP 배열에 저장
14
+ */
15
+ function longestCommonSubsequence ( text1 : string , text2 : string ) : number {
16
+ const m = text1 . length ,
17
+ n = text2 . length ;
18
+
19
+ const dp = Array . from ( { length : m + 1 } , ( ) => Array ( n + 1 ) . fill ( 0 ) ) ;
20
+
21
+ for ( let i = 1 ; i <= m ; i ++ ) {
22
+ for ( let j = 1 ; j <= n ; j ++ ) {
23
+ if ( text1 [ i - 1 ] === text2 [ j - 1 ] ) {
24
+ dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + 1 ;
25
+ } else {
26
+ dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ;
27
+ }
28
+ }
29
+ }
30
+ return dp [ m ] [ n ] ;
31
+ }
You can’t perform that action at this time.
0 commit comments