File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed 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
+ * @param {string } text1
4
+ * @param {string } text2
5
+ * @return {number }
6
+ */
7
+ var longestCommonSubsequence = function ( text1 , text2 ) {
8
+ let m = text1 . length
9
+ let n = text2 . length
10
+ let dp = Array . from ( new Array ( m + 1 ) , ( ) => new Array ( n + 1 ) . fill ( 0 ) )
11
+
12
+ for ( let i = 0 ; i < m ; i ++ ) {
13
+ for ( let j = 0 ; j < n ; j ++ ) {
14
+ if ( text1 [ i ] === text2 [ j ] ) {
15
+ dp [ i + 1 ] [ j + 1 ] = dp [ i ] [ j ] + 1
16
+ } else {
17
+ dp [ i + 1 ] [ j + 1 ] = Math . max ( dp [ i + 1 ] [ j ] , dp [ i ] [ j + 1 ] )
18
+ }
19
+ }
20
+ }
21
+ return dp [ m ] [ n ]
22
+ }
23
+
24
+ let lcs = longestCommonSubsequence ( 'abc' , 'acbd' )
25
+ // let lcs = longestCommonSubsequence("ezupkr", "ubmrapg")
26
+ // let lcs = longestCommonSubsequence("bsbininm", "jmjkbkjkv")
27
+
28
+ console . log ( 'lcs: ' , lcs )
You can’t perform that action at this time.
0 commit comments