Amazon Interview Question
Country: India
Interview Type: In-Person
bool rotation(char *str1 , char *str2)
{
if(str1 == NULL || str2 == NULL)
return 0;
if(strlen(str1) != strlen(str2))
return 0;
char *temp = new char[sizeof(str1) * 2 + 1];
strcat(temp,str1);
strcat(temp,str1);
char *ptr =strstr(temp,str2);
delete temp;
if(ptr == NULL)
return 0;
else
return 1;
}
char * move1char(char *str)
{
char temp=*str;
static char *strtemp=new char[strlen(str)];
int i=0,len=strlen(str);
while(i<len)
{
strtemp[i]=str[i+1];
i++;
}
strtemp[len-1]=temp;
return(strtemp);
}
bool cyclic(char *str1,char *str2)
{
int m=0,len=strlen(str1);
char *strtemp=new char[strlen(str1)];
if(strlen(str1) != strlen(str2))
return false;
strtemp=str2;
for(int i=0;i<len;i++)
{
if(!strncmp(str1,strtemp,len))
return true;
else
strtemp=move1char(strtemp);
}
return(false);
}
void rotationalequi(){
char *A="Helluo";
char *B="elloH";
char *tmp=B;
char *CC=(char*)malloc(sizeof(char)*strlen(B)*2+1);
char *C=CC;
int counter=0;
while(1){
while(*tmp){
*C++=*tmp++;
}
counter++;
if(counter==2){
*C='\0';
break;
}
tmp=B;
}
C=CC;
tmp=A;
cout << " " << C;
while(*C){
while((*C==*tmp)&&(*tmp)){
C++;
tmp++;
}
if(!*tmp){
cout << " found ";
break;
}
else{
tmp=A;
}
C++;
}
free (CC);
};
Easy. Append one of those strings with itself;
- Arvind October 03, 2011so if I am given to check if vindar and darvin are rotational equivalents, just append vindar to itself. Now i have vindarvindar and ANY rotational equivalent of the string will be a substring of this string!