File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ int longestCommonSubsequence (char * text1 , char * text2 ) {
2
+ int m = strlen (text1 );
3
+ int n = strlen (text2 );
4
+
5
+ int dp [m + 1 ][n + 1 ]; // dp[i][j] represents the length of the LCS of text1[0...i-1] and text2[0...j-1]
6
+
7
+ // Initialize the first row and column to 0
8
+ for (int i = 0 ; i <= m ; i ++ ) {
9
+ dp [i ][0 ] = 0 ;
10
+ }
11
+ for (int j = 0 ; j <= n ; j ++ ) {
12
+ dp [0 ][j ] = 0 ;
13
+ }
14
+
15
+ // Dynamic programming approach to fill the dp array
16
+ for (int i = 1 ; i <= m ; i ++ ) {
17
+ for (int j = 1 ; j <= n ; j ++ ) {
18
+ if (text1 [i - 1 ] == text2 [j - 1 ]) {
19
+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 ;
20
+ } else {
21
+ dp [i ][j ] = (dp [i - 1 ][j ] > dp [i ][j - 1 ]) ? dp [i - 1 ][j ] : dp [i ][j - 1 ];
22
+ }
23
+ }
24
+ }
25
+
26
+ return dp [m ][n ];
27
+ }
You can’t perform that action at this time.
0 commit comments