Skip to content

Instantly share code, notes, and snippets.

@mpenkov
Last active December 16, 2015 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpenkov/5385855 to your computer and use it in GitHub Desktop.
Save mpenkov/5385855 to your computer and use it in GitHub Desktop.
Coding for Interviews: Reverse Words
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define SPACE ' '
void
reverse_words(char *sent, size_t len)
{
size_t i;
size_t start;
size_t end;
char tmp;
/*
* Reverse the entire string.
*/
for (i = 0; i < len/2; ++i)
{
tmp = sent[i];
sent[i] = sent[len-1-i];
sent[len-1-i] = tmp;
}
/*
* Find the first non-space element.
*/
for (start = 0; start < end && sent[start] == SPACE; ++start)
;
/*
* Reverse individual words in the string.
* Words are delimited by SPACE.
*/
while (start < len)
{
for (end = start+1; end < len && sent[end] != SPACE; ++end)
;
for (i = start; i < (start+end)/2; ++i)
{
tmp = sent[i];
sent[i] = sent[end-1-i+start];
sent[end-1-i+start] = tmp;
}
start = end+1;
}
}
int
main(int argc, char **argv)
{
char *sent = NULL;
if (argc == 1)
{
char const *tmp = "Coding for Interviews contains too many gifs.";
sent = (char *)malloc(sizeof(char)*strlen(tmp));
assert(sent);
strcpy(sent, tmp);
}
else
{
sent = (char *)malloc(sizeof(char)*strlen(argv[1]));
assert(sent);
strcpy(sent, argv[1]);
}
reverse_words(sent, strlen(sent));
printf("`%s'\n", sent);
free(sent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment