File tree Expand file tree Collapse file tree 3 files changed +71
-1
lines changed
solution/1100-1199/1143.Longest Common Subsequence Expand file tree Collapse file tree 3 files changed +71
-1
lines changed Original file line number Diff line number Diff line change 55
55
56
56
<!-- 这里可写通用的实现逻辑 -->
57
57
58
- 动态规划法。
58
+ ** 方法一:动态规划 **
59
59
60
60
定义 ` dp[i][j] ` 表示 ` text1[0:i-1] ` 和 ` text2[0:j-1] ` 的最长公共子序列(闭区间)。
61
61
@@ -156,6 +156,31 @@ func max(a, b int) int {
156
156
}
157
157
```
158
158
159
+ ### ** JavaScript**
160
+
161
+ ``` js
162
+ /**
163
+ * @param {string} text1
164
+ * @param {string} text2
165
+ * @return {number}
166
+ */
167
+ var longestCommonSubsequence = function (text1 , text2 ) {
168
+ const m = text1 .length ;
169
+ const n = text2 .length ;
170
+ const dp = new Array (m + 1 ).fill (0 ).map (() => new Array (n + 1 ).fill (0 ));
171
+ for (let i = 1 ; i <= m; ++ i) {
172
+ for (let j = 1 ; j <= n; ++ j) {
173
+ if (text1[i - 1 ] == text2[j - 1 ]) {
174
+ dp[i][j] = dp[i - 1 ][j - 1 ] + 1 ;
175
+ } else {
176
+ dp[i][j] = Math .max (dp[i - 1 ][j], dp[i][j - 1 ]);
177
+ }
178
+ }
179
+ }
180
+ return dp[m][n];
181
+ };
182
+ ```
183
+
159
184
### ** ...**
160
185
161
186
```
Original file line number Diff line number Diff line change @@ -142,6 +142,31 @@ func max(a, b int) int {
142
142
}
143
143
```
144
144
145
+ ### ** JavaScript**
146
+
147
+ ``` js
148
+ /**
149
+ * @param {string} text1
150
+ * @param {string} text2
151
+ * @return {number}
152
+ */
153
+ var longestCommonSubsequence = function (text1 , text2 ) {
154
+ const m = text1 .length ;
155
+ const n = text2 .length ;
156
+ const dp = new Array (m + 1 ).fill (0 ).map (() => new Array (n + 1 ).fill (0 ));
157
+ for (let i = 1 ; i <= m; ++ i) {
158
+ for (let j = 1 ; j <= n; ++ j) {
159
+ if (text1[i - 1 ] == text2[j - 1 ]) {
160
+ dp[i][j] = dp[i - 1 ][j - 1 ] + 1 ;
161
+ } else {
162
+ dp[i][j] = Math .max (dp[i - 1 ][j], dp[i][j - 1 ]);
163
+ }
164
+ }
165
+ }
166
+ return dp[m][n];
167
+ };
168
+ ```
169
+
145
170
### ** ...**
146
171
147
172
```
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } text1
3
+ * @param {string } text2
4
+ * @return {number }
5
+ */
6
+ var longestCommonSubsequence = function ( text1 , text2 ) {
7
+ const m = text1 . length ;
8
+ const n = text2 . length ;
9
+ const dp = new Array ( m + 1 ) . fill ( 0 ) . map ( ( ) => new Array ( n + 1 ) . fill ( 0 ) ) ;
10
+ for ( let i = 1 ; i <= m ; ++ i ) {
11
+ for ( let j = 1 ; j <= n ; ++ j ) {
12
+ if ( text1 [ i - 1 ] == text2 [ j - 1 ] ) {
13
+ dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + 1 ;
14
+ } else {
15
+ dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ;
16
+ }
17
+ }
18
+ }
19
+ return dp [ m ] [ n ] ;
20
+ } ;
You can’t perform that action at this time.
0 commit comments