Bloomberg LP Interview Question
Financial Software Developersvoid reverse_word(char* begin, char*end)
{
//*end is a whitespace of '\0'
// Don't use any length pointer.
--end;
while(begin < end){
swap(*begin,*end);
begin++;end--;
}
}
void reverse_sentence(char* sentence)
{
char*begin= sentence, *end=sentence;
while(*end){
while(*end || *end != ' ') {
end++;
}
reverse_word(begin,end); // reverses each word.
if(*end) {begin = end+1;end = begin;}
}
reverse_word(sentence,end); // reverses the entire sentence
}
void reverseWords( char str[] ){
int start = 0, end = 0, length;
length = strlen(str);
/* Reverse entire string */
reverseString(str, start, length - 1);
while( end < length ){
if( str[end] != ' ' ){ /* Skip non-word characters */
/* Save position of beginning of word */
start = end;
/* Scan to next non-word character */
while( end < length && str[end] != ' ' )
end++;
/* Back up to end of word */
end--;
/* Reverse word */
reverseString( str, start, end );
}
end++; /* Advance to next token */
}
}
void reverseString( char str[], int start, int end ){
char temp;
while( end > start ){
/* Exchange characters */
temp = str[start];
str[start] = str[end];
str[end] = temp;
/* Move indices towards middle */
start++; end--;
}
}
First you need to have a clear definition of what a "word" is. Essentially you can solve this task by storing all words in a container and then reversing the container. The more difficult more is to parse to string.
- Leon January 06, 2009