File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 문제 설명
3
+ * - 두 문자열의 가장 긴 공통 부분 문자열의 길이를 반환
4
+ * - 대표적인 DP 문제
5
+ *
6
+ * 아이디어
7
+ * 1) 브루투포스 O(n^2)
8
+ * 2) DP O(n^2)
9
+ * - dp[i][j]를 만들어서 text1[i]와 text2[j]가 같은 경우 dp[i][j] = dp[i-1][j-1] + 1
10
+ * - 다른 경우 dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1])
11
+ */
12
+
13
+ function longestCommonSubsequence ( text1 : string , text2 : string ) : number {
14
+ const dp = Array . from ( { length : text1 . length + 1 } , ( ) =>
15
+ Array ( text2 . length + 1 ) . fill ( 0 )
16
+ ) ;
17
+
18
+ for ( let i = 1 ; i <= text1 . length ; i ++ ) {
19
+ for ( let j = 1 ; j <= text2 . length ; j ++ ) {
20
+ if ( text1 [ i - 1 ] === text2 [ j - 1 ] ) {
21
+ dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + 1 ;
22
+ } else {
23
+ dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ;
24
+ }
25
+ }
26
+ }
27
+ return dp [ text1 . length ] [ text2 . length ] ;
28
+ }
You can’t perform that action at this time.
0 commit comments