Advertisement
tzanany

Longest Common Subsequence(Question-3_Spring2011)

Apr 30th, 2012
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. int findmax(char **commons, int size) {
  6.     int i, max=0, maxPlace;
  7.     //Find The Longest String
  8.     for(i=0;i<size;i++) {
  9.         if(strlen(commons[i]) > max) {
  10.             max = strlen(commons[i]);
  11.             maxPlace = i;
  12.         }
  13.     }
  14.     return maxPlace; // Return The Longest String Index
  15. }
  16.  
  17. char *strdupCommons(char *str, int flag)
  18. {
  19.     int i;
  20.     char *ptr;
  21.    
  22.     if(flag) { //We Need Shorter String
  23.         // Customized Strdup
  24.         for(i=0;i<strlen(str)-1;i++)
  25.             ptr = (char *)malloc( (i+1) * sizeof(char) );
  26.  
  27.         ptr[i]='\0';
  28.         for(i-=1;i>=0;i--)
  29.             ptr[i]=str[i];
  30.     }
  31.     else {    // Near The End We Dont Need Shorter String
  32.         ptr = strdup(str); // Regular Strdup
  33.     }
  34.  
  35.     return ptr;
  36. }
  37.  
  38. void main() {
  39.     char str1[] = "C exam question 3 fall 2011";
  40.     char str2[] = "C program exam fall 2011 questions";
  41.     char **commons = NULL;  // Commons String Array
  42.     char temp[100];         // Temporary String
  43.     int flag = 0;           // 0 - UnCommon / 1 - Common
  44.     int i, j = 0, comi = 0; // Indexes
  45.  
  46.     for(i=0;str1[i]!='\0';i++) { // Run On Str1
  47.         strncpy(temp,&str1[j],i+1); // Copy Str1(From Place j To i+1) To Temp - SubString
  48.         temp[i+1]='\0'; // Close The SubString
  49.         if(strstr(str2,temp) != NULL && str1[i+1]!='\0') // Check If The SubString Exist On Str2
  50.             flag=1;
  51.         else if(flag==1) { // Not Exist Anymore But Was Exist
  52.             commons = (char **) realloc(commons, (comi+1) * sizeof(char *)); //Allocate Memory For Strings Array
  53.             if(str1[i+1]!='\0') // Check If We Near The End, Send Flag 1 To strdupCommons
  54.                 commons[comi] = strdupCommons(temp,1);
  55.             else // Send Flag 0 To strdupCommons
  56.                 commons[comi] = strdupCommons(temp,0);
  57.             comi++; // Make The Commons Index(For The Strings Array) Bigger;
  58.             flag = 0; // Flag Is On UnCommon State
  59.             j=i; // j is now like i (Start Substring from j)
  60.             //puts(commons[comi-1]); //Print The Common Strings
  61.         }
  62.         else
  63.             j=i; // j is now like i (Start Substring from j)
  64.     }
  65.     printf("Longest Common Subsequence Is: %s With %d Chars\n", commons[findmax(commons,comi)], strlen(commons[findmax(commons,comi)]) );
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement