Advertisement
Guest User

Untitled

a guest
Nov 19th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define N 1001
  5. #define max(x, y) ((x > y) ? x : y)
  6.  
  7.  
  8. int L[N][N];
  9.  
  10.  
  11. int lcs_length(char A[N], char B[N]) {
  12.     int i, j, m = strlen(A), n = strlen(B);
  13.  
  14.     for (i = m; i >= 0; i--) {
  15.         for (j = n; j >= 0; j--) {
  16.             if (A[i] == '\0' || B[j] == '\0') {
  17.                 L[i][j] = 0;
  18.             } else if (A[i] == B[j]) {
  19.                 L[i][j] = 1 + L[i + 1][j + 1];
  20.                 } else {
  21.                 L[i][j] = max(L[i + 1][j], L[i][j + 1]);
  22.             }
  23.         }
  24.     }
  25.  
  26.     return L[0][0];
  27. }
  28.  
  29.  
  30. int main () {
  31.     int i = 0, j = 0, m, n, length;
  32.     char a[N], b[N];
  33.  
  34.     scanf("%s", a);
  35.     scanf("%s", b);
  36.  
  37.     m = strlen(a);
  38.     n = strlen(b);
  39.  
  40.     length =  lcs_length(a, b);
  41.  
  42.     if (length == 0) {
  43.         printf("Empty");
  44.  
  45.         return 0;
  46.     }
  47.  
  48.     while (i < m && j < n) {
  49.         if (a[i] == b[j]) {
  50.             printf("%c", a[i]);
  51.  
  52.             i++;
  53.             j++;
  54.         } else if (L[i+1][j] >= L[i][j+1]) {
  55.             i++;
  56.             } else {
  57.             j++;
  58.         }
  59.     }
  60.  
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement