File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -247,6 +247,45 @@ public class DPExampleUtil {
247
247
}
248
248
return dp[n];
249
249
}
250
+
251
+
252
+ /**
253
+ * 6、两个字符串的最长公共子序列问题
254
+ *
255
+ * 例如“ab1cd2ef345gh”和“opq123rs4tx5yz”的最长公共子序列为“12345”。即在两个字符串所有相等的子序列里最长的。所以返回子序列的长度5
256
+ *
257
+ **/
258
+ public static int lcse (char [] str1 , char [] str2 ) {
259
+
260
+ int [][] dp = new int [str1. length][str2. length];
261
+
262
+ dp[0 ][0 ] = str1[0 ] == str2[0 ] ? 1 : 0 ;
263
+
264
+
265
+ // 填第0列的所有值
266
+ // 一旦st1r的i位置某个字符等于str2的0位置,那么之后都是1
267
+ for (int i = 1 ; i < str1. length; i++ ) {
268
+ dp[i][0 ] = Math . max(dp[i - 1 ][0 ], str1[i] == str2[0 ] ? 1 : 0 );
269
+ }
270
+ // 填第0行的所有值
271
+ // 一旦str2的j位置某个字符等于str1的0位置,那么之后都是1
272
+ for (int j = 1 ; j < str2. length; j++ ) {
273
+ dp[0 ][j] = Math . max(dp[0 ][j - 1 ], str1[0 ] == str2[j] ? 1 : 0 );
274
+ }
275
+
276
+ for (int i = 1 ; i < str1. length; i++ ) {
277
+ for (int j = 1 ; j < str2. length; j++ ) {
278
+
279
+ // dp[i - 1][j]表示可能性2
280
+ // dp[i][j - 1] 表示可能性3
281
+ dp[i][j] = Math . max(dp[i - 1 ][j], dp[i][j - 1 ]);
282
+ if (str1[i] == str2[j]) {
283
+ dp[i][j] = Math . max(dp[i][j], dp[i - 1 ][j - 1 ] + 1 );
284
+ }
285
+ }
286
+ }
287
+ return dp[str1. length - 1 ][str2. length - 1 ];
288
+ }
250
289
251
290
252
291
}
You can’t perform that action at this time.
0 commit comments