Friday, November 15, 2013

C Program to find if Two strings are Rotations of each other

Approach#1: The naive approach will be to find the first character occurrence in another string and then check whether the consecutive characters match with the other strings or not.

Approach#2:
The solution here is pretty simple:
i)  first append string which is rotated, to itself.
ii) find if second string is a substring of above appended string, if yes then return true, else return false.

here's the Implementation of the above algortihm:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int check_rotations(char* str1, char* str2)
{
    int x=strlen(str1);
    int y=strlen(str2);

    if(x!=y)
        return 0;

    char *temp=(char*) malloc(sizeof(char)*(2*x+1));
    strcpy(temp,str1);
    strcat(temp,str1);
    return strstr(temp,str2);

}

int main()
{
    char str1[]="DABC";
    char str2[]="ABCD";
    if(check_rotations(str1,str2))
        printf("strings are rotations of each other");
    else
        printf("strings are not rotations of each other");
}

Viva La Raza
Sid



No comments:

Post a Comment