We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 520aa0c + cd7c86c commit be373c1Copy full SHA for be373c1
c/1143-longest-common-subsequence.c
@@ -0,0 +1,27 @@
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
+}
0 commit comments