Print the longest prefix of the given string which is also the suffix of the same string in C Program.

CServer Side ProgrammingProgramming

Given a string in which we have to check that the length of the longest prefix which is also a suffix of the string like there is a string “abcab” so here “ab” is of length 2 and is the longest substring with same prefix and suffix.

Example

Input: str[] = { “aabbccdaabbcc” }
Output: 6
Input: abdab
Output: 2

If we will start the pointer from start and end of the string than they will get overlapped at some point so instead of doing that we will break the string from middle and start matching left and right string. If they are equal return size of any one of the matched string else try for shorter lengths on both the sides.

Algorithm

int longest(char str[], int n)
START
STEP 1 : DECLARE length AS 0 AND i AS n/2
STEP 2 : IF n < 2 THEN
   RETURN 1
STEP 3 :LOOP WHILE TILL str[i]!='\0'
   IF str[i] == str[length] THEN,
      INCREMENT length BY 1
      INCREMENT i BY 1
   ELSE
      IF length == 0 THEN,
         INCREMENT i BY 1
      ELSE
         DECREMENT length BY 1
      END IF
   END IF
END WHILE
RETURN length
STOP

Example

#include <stdio.h>
int longest(char str[], int n){
   int length = 0, i = n/2;
   if( n < 2 )
      return 1;
   while( str[i]!='\0' ){
      //When we find the character like prefix in suffix,
      //we will move the length and i to count the length of the similar prefix and suffix
      if (str[i] == str[length]){
         ++length;
         ++i;
      } else //When prefix and suffix not equal{
         if(length == 0)
            ++i;
         else
            --length;
      }
   }
   return length;
}
int main(int argc, char const *argv[]){
   char str[] = {"abccmmabcc"};
   int n = sizeof(str)/sizeof(str[0]);
   int length = longest(str, n);
   printf("Length = %d", length);
   return 0;
}

Output

If we run above program then it will generate following output:

Length = 4
raja
Published on 22-Aug-2019 08:36:54
Advertisements