Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday 24 March 2019

The Interview Question Today#20 (15-3-19)

Question:
A Program to check if strings are rotations of each other or not


Example:

INPUT
String1 = "ABCDE"
String2 = "DEABC"

OUTPUT
Strings are rotations of each other

Solution:

Approach:

1. Concatenate s1 with s1

2. Now, if s2 is a substring of above concatenation, then s1 and s2 are rotations of each other.


C program:


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

/* Function checks if passed strings (str1 and str2) are rotations of each other */
int areRotations(char *str1, char *str2)
{
  int size1   = strlen(str1);
  int size2   = strlen(str2);
  char temp[200];
  void *ptr;

  if (size1 != size2)
     return 0;

  strcat(temp, str1);
  strcat(temp, str1);

  ptr = strstr(temp, str2);
  free(temp);
  if (ptr != NULL)
    return 1;
  else
    return 0;
}

int main()
{
    char str1[100];
    char str2[100];
    printf("Enter the First String: ");
    scanf("%s",str1);
    printf("Enter the Second String: ");
    scanf("%s",str2);


    if (areRotations(str1, str2))
       printf("Strings are rotations of each other");
    else
       printf("Strings are not rotations of each other");

    return 0;
}

Output:

Enter the First String: ABCD
Enter the Second String: CDAB
Strings are rotations of each other

0 comments:

Post a Comment