File tree 3 files changed +74
-0
lines changed
1143_longest_common_subsequence
3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ all :
2
+ gcc -O1 -o test lcs.c
Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <string.h>
4
+
5
+
6
+ static int max (int a , int b )
7
+ {
8
+ return a > b ? a : b ;
9
+ }
10
+
11
+ int longestCommonSubsequence (char * text1 , char * text2 )
12
+ {
13
+ int i , j ;
14
+ int l1 = strlen (text1 );
15
+ int l2 = strlen (text2 );
16
+ int * * dp = malloc ((l1 + 1 ) * sizeof (int * ));
17
+ for (i = 0 ; i < l1 + 1 ; i ++ ) {
18
+ dp [i ] = malloc ((l2 + 1 ) * sizeof (int ));
19
+ }
20
+ memset (dp [0 ], 0 , (l2 + 1 ) * sizeof (int ));
21
+ for (i = 1 ; i <= l1 ; i ++ ) {
22
+ dp [i ][0 ] = 0 ;
23
+ }
24
+
25
+ for (i = 1 ; i <= l1 ; i ++ ) {
26
+ for (j = 1 ; j <= l2 ; j ++ ) {
27
+ if (text1 [i - 1 ] == text2 [j - 1 ]) {
28
+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 ;
29
+ } else {
30
+ dp [i ][j ] = max (dp [i - 1 ][j ], dp [i ][j - 1 ]);
31
+ }
32
+ }
33
+ }
34
+ return dp [l1 ][l2 ];
35
+ }
36
+
37
+ int main (int argc , char * * argv )
38
+ {
39
+ if (argc != 3 ) {
40
+ fprintf (stderr , "Usage: ./test s1 s2\n" );
41
+ exit (-1 );
42
+ }
43
+
44
+ printf ("%d\n" , longestCommonSubsequence (argv [1 ], argv [2 ]));
45
+ return 0 ;
46
+ }
Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+
3
+ using namespace std ;
4
+
5
+ class Solution {
6
+ public:
7
+ int longestCommonSubsequence (string text1, string text2) {
8
+ int l1 = text1.length ();
9
+ int l2 = text2.length ();
10
+ vector<int > dp (l2 + 1 );
11
+ int up = 0 ;
12
+ for (int i = 1 ; i <= l1; i++) {
13
+ int left_up = 0 ;
14
+ for (int j = 1 ; j <= l2; j++) {
15
+ up = dp[j];
16
+ if (text1[i - 1 ] == text2[j - 1 ]) {
17
+ dp[j] = left_up + 1 ;
18
+ } else {
19
+ dp[j] = max (up, dp[j - 1 ]);
20
+ }
21
+ left_up = up;
22
+ }
23
+ }
24
+ return dp[l2];
25
+ }
26
+ };
You can’t perform that action at this time.
0 commit comments