Monday, January 28, 2013

Reverse the String in such a way that if the input is 'i am the best' output should be 'best the am i'.

This question was asked to me in Athena Health Interview . The solution is same as rotate array by k times .

Steps:

1. reverse the whole string (tseb eht ma i).
2. reverse the strings separated by space (best the am i).

Assume that isspace() funtion looks like this
int isspace(char ch)
{
   // ascii value of space is 32
     if((int)ch==32)
        return 1;
     return 0;
}

Code:(in C)

void reverse(char* str)
{
int length=strlen(str);
if(length < 2 )
return;
reverse_string(str,0,length-1);
int temp=0,first,last;
while(true)
{
while(isspace(str[temp]))
temp++;
if(str[temp]=='/0')
break;
first=temp;
while(! isspace(str[temp]) && str[temp]!='/0')
temp++;
last=temp-1;
if(first < last) 
reverse_string(str,first,last);
}
}

void reverse_string(char *str,int first,int last)
{
char temp;
while(first < last )

        {
temp=str[first];
str[first]=str[last];
str[last]=temp;
}
}

Please let me know if there is any bug in the above code and your suggestions are always welcome .

1 comment:

jaanavalenzuela said...

The Wynn Plaza - Mapyro
Find The Wynn Plaza in Las Vegas, Nevada, United 보령 출장안마 States of 전라남도 출장마사지 America - Mapyro® USA Realtime Reviews, 통영 출장샵 Reviews and 진주 출장마사지 Ratings. 용인 출장마사지