File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 두 문자열에서 공통으로 나타나는 부분 수열 중 가장 긴 것의 길이를 찾는 문제
3
+ *
4
+ * 다이나믹 프로그래밍(DP): 작은 문제의 결과를 저장해서 큰 문제를 해결하는 방법
5
+ * 시간 복잡도: O(m × n)
6
+ * 공간복잡도: O(min(m, n))
7
+ */
8
+ /**
9
+ * @param {string } text1
10
+ * @param {string } text2
11
+ * @return {number }
12
+ */
13
+ var longestCommonSubsequence = function ( text1 , text2 ) {
14
+ // 더 짧은 문자열을 text2로 만들어 공간 절약
15
+ if ( text1 . length < text2 . length ) {
16
+ [ text1 , text2 ] = [ text2 , text1 ] ;
17
+ }
18
+
19
+ const m = text1 . length ;
20
+ const n = text2 . length ;
21
+
22
+ // 1차원 배열 2개만 사용 (이전 행, 현재 행)
23
+ let prev = Array ( n + 1 ) . fill ( 0 ) ;
24
+ let curr = Array ( n + 1 ) . fill ( 0 ) ;
25
+
26
+ for ( let i = 1 ; i <= m ; i ++ ) {
27
+ for ( let j = 1 ; j <= n ; j ++ ) {
28
+ if ( text1 [ i - 1 ] === text2 [ j - 1 ] ) {
29
+ curr [ j ] = prev [ j - 1 ] + 1 ;
30
+ } else {
31
+ curr [ j ] = Math . max ( prev [ j ] , curr [ j - 1 ] ) ;
32
+ }
33
+ }
34
+ // 다음 반복을 위해 배열 교체
35
+ [ prev , curr ] = [ curr , prev ] ;
36
+ curr . fill ( 0 ) ;
37
+ }
38
+
39
+ return prev [ n ] ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments