File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * <a href="https://leetcode.com/problems/longest-common-subsequence/">week8-4.longest-common-subsequence</a>
3
+ * <li>Description: Given two strings text1 and text2, return the length of their longest common subsequence</li>
4
+ * <li>Topics: String, Dynamic Programming</li>
5
+ * <li>Time Complexity: O(M×N), Runtime 11ms</li>
6
+ * <li>Space Complexity: O(M×N), Memory 50.97MB</li>
7
+ */
8
+
9
+ class Solution {
10
+ public int longestCommonSubsequence (String text1 , String text2 ) {
11
+ int m = text1 .length ();
12
+ int n = text2 .length ();
13
+ int [][] dp = new int [m + 1 ][n + 1 ];
14
+ for (int i = 1 ; i <= m ; i ++) {
15
+ char c1 = text1 .charAt (i - 1 );
16
+ for (int j = 1 ; j <= n ; j ++) {
17
+ char c2 = text2 .charAt (j - 1 );
18
+
19
+ if (c1 == c2 ) {
20
+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 ;
21
+ } else {
22
+ dp [i ][j ] = Math .max (dp [i - 1 ][j ], dp [i ][j - 1 ]);
23
+ }
24
+ }
25
+ }
26
+
27
+ return dp [m ][n ];
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments